Math.max vs ternary vs if

JavaScript performance comparison

Revision 11 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)
a = Math.max(a, b);
pending…
static max (if)
if (b > a) {
  a = b;
}
pending…
static max (ternary)
a = 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.

Add a comment