Math.max vs ternary vs if

JavaScript performance comparison

Revision 9 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 = 11,
      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
static max (Math)
a = Math.max(a, b);
pending…
static max (if)
if (b > a) {
  a = b;
}
pending…
static max (ternary)
a = a > b ? a : b;
pending…
max (Math)
c = Math.max(c, d);
pending…
max (if)
if (d > c) {
  c = d;
}
pending…
max (ternary)
c = c > d ? c : d;
pending…
random bitwise
c = c & ((d-c) >> 31) | d & (~(d-c) >> 31);
 
pending…
static bitwise
c = b & ((a-b) >> 31) | a & (~(a-b) >> 31);
 
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