Math.max vs ternary vs if

JavaScript performance comparison

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

Comment form temporarily disabled.

Add a comment