Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 525
Jeff Avatar asked Apr 06 '10 17:04

Jeff


People also ask

Is ternary a logical operator?

The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy.

Is ternary the same as if else?

The conditional operator – also known as the ternary operator – is an alternative form of the if/else statement that helps you to write conditional code blocks in a more concise way. First, you need to write a conditional expression that evaluates into either true or false .

Which is better ternary operator or if else?

If condition is preferred in case if program requires executing only on true block. In this case, it is necessary to work around to use Ternary Operator. Nested Ternary Operator is not readable and can not be debugged easily. If else is more readable and easier to debug in case of issue.

Is ternary faster than if else JS?

In terms of speed there should be no difference. Unless you are using a really bad javascript implementation. The slowest part of both statements is the branching. Nice answer!


1 Answers

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.

like image 114
charlie roberts Avatar answered Sep 20 '22 18:09

charlie roberts