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

后端 未结 7 1599
情歌与酒
情歌与酒 2020-11-30 02:06

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?

7条回答
  •  再見小時候
    2020-11-30 02:40

    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.

提交回复
热议问题