Math.min/max vs ternary vs if

JavaScript performance comparison

Revision 3 of this test case created

Info

What's the fastest way to compare numbers? All conditionals are designed to fail.

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var
      a = Math.random(),
      b = Math.random(),
      c = Math.random(),
      d = Math.random()
    ;
};
</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
min (Math)
c = Math.min(a, b, c, d);
pending…
max (Math)
c = Math.max(a, b ,c, d);
pending…
min (if)
if (a < b) {
  c = a;
} else if(b < c){
  c = b;
}else if(c < d){
  c = c;
}else{
  c = d;
}
 
pending…
max (if)
if (a > b) {
  c = a;
} else if(b > c){
  c = b;
}else if(c > d){
  c = c;
}else{
  c = d;
}
 
pending…
min (ternary)
c = a > b ? a : b > c ? b : c > d ? c : d;
pending…
max (ternary)
c = a < b ? a :  b < c ? b : c < d ? c : d;
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

0 comments

Add a comment