Math.max vs ternary vs if

JavaScript performance comparison

Revision 12 of this test case created by David

Info

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

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    a = 10;
    b = 11;
};
</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…

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:

1 comment

David (revision owner) commented :

Previous versions contained a bug: the variables a, b, etc. were declared outside of the scope of the testing functions. Also, using random numbers can lead to different results, which is only interesting with a large amount of samples. Finally, the result is stored, no matter what, making this bench more reliable (the static max wasn't storing anything if a > b, making this test an instruction less than the others).

Add a comment