Math.min/max vs ternary vs if

JavaScript performance comparison

Revision 2 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 = 10,
      b = 100,
      c = 40,
      d = 30
    ;
};
</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);
pending…
max (Math)
c = Math.max(a, b ,c, d);
pending…
min (if)
if (b < a) {
  c = a;
} else if(b < c){
  c = b;
}else if(c < d){
  c = d;
}
 
pending…
max (if)
if (a < b) {
  c = a;
} else if(b > c){
  c = b;
}else if(c > d){
  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