Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
727 views
in Technique[技术] by (71.8m points)

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

Which method is faster or more responsive in javascript, if-else, the ternary operator or logical OR? Which is advisable to use, for what reasons?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.5 - 2x 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...