Math.max vs ternary vs if

JavaScript performance comparison

Revision 12 of this test case created by David


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

Preparation code

Benchmark.prototype.setup = function() {
    a = 10;
    b = 11;

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);
static max (if)
var r;
if (a > b) {
  r = a;
} else {
  r = b
static max (ternary)
var r = a > b ? a : b;

Compare results of other browsers


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).

Comment form temporarily disabled.

Add a comment