Is ternary operator, if-else or logical OR faster in javascript?

Seems like nobody did any actual profiling. Here’s the code I used:

test = function() {
    for (var i = 0; i < 10000000; i++) {
        var a = i < 100 ? 1 : 2;

        /*
        if(i < 100) {
            var a = 1;
        }else{
            var a = 2;
        }
        */
    }
}

test();

Using the if/else block instead of the ternary operator yields a 1.52x performance increase in Google Chrome v21 under OS X Snow Leopard.

As one use case where this is very important, synthesizing real-time audio is becoming more and more common with JavaScript. This type of performance difference is a big deal when an algorithm is running 44100 times a second.

Leave a Comment