Math.max vs ternary vs if

JavaScript performance comparison

Revision 14 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;
    var b = 22;
   
    var maxMath = Math.max;
    var maxIf = function(a, b) {
      if (a < b) {
        return b;
      }
      return a;
    }
};
</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)
var r = Math.max(a, b);
pending…
static max (if)
var r;
if (a > b) {
  r = a;
} else {
  r = b
}
pending…
static max (ternary)
var r = a > b ? a : b;
pending…
maxMath
var r = maxMath(a, b);
pending…
maxIf
var r = maxIf(a, b);
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