Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are ternary statements faster than if/then/else statements in javascript?

I see a lot of:

var something = (is_something_true()) ? 3 : 4;

in javascript. Is this faster than

var something;
if (is_something_true()) {
    something = 3;
} else {
    something = 4;
}

Or is it written concisely for convenience?

like image 832
rjkaplan Avatar asked Jul 06 '12 20:07

rjkaplan


4 Answers

Please enjoy this -- if difference is statistically valid then the result (true or false) also matters -- clearly this is just other stuff on the machine having an impact on browser performance:

Here is the link

different results!

There is a fundamental difference between the two, the ternary statements are expressions and not flow of control. If there is a case where someone writes it as a ternary expression instead of a standard if / than / else, when both would work the same they are (in my opinion) making the code harder to read without good reason.

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.

like image 62
Hogan Avatar answered Oct 11 '22 18:10

Hogan


You should write for readability first and tiny micro-optimizations one-hundred and fifty-second. The first form is easier to read in many cases and there probably isn't much of a difference in performance one way or the other.

(Even if you disagree and think the second form is easier to read, asking about the relative performance difference is still the wrong question.)

like image 41
Wayne Avatar answered Oct 11 '22 17:10

Wayne


Here is the statisitics:enter image description here

After multiple tests and observations, it can be concluded,that the most cases the ternary operator(?:) is slower,than if/else.

like image 24
Engineer Avatar answered Oct 11 '22 17:10

Engineer


Yes, there is negligible difference between the two.

However the difference is so small that it doesn't matter which one you use (I prefer if/else) because they help in readability which would save you a lot of time if someone is going through your code or maybe you yourself are maybe after say 3 months or so.

For those people who want to check the difference try this code:

// declarations  
var num1 = 10, num2, i = 0, startTime, endTime, x, y;

// start timer
startTime = Math.floor((new Date()).getTime());

for(; i < 1e8; i++) {
  // first part if /else
  if(x == 10)
    y = x;
  else
    y = 0;

  // second part ternary
  y = (x == 10) ? x : 0;
}

// end timer     
endTime = Math.floor((new Date()).getTime() - startTime);
document.write("Time taken " + endTime + " ms");  

Note: Comment one of the part and execute the code and run the loop for large number of iterations (above code millions of iterations).

Tip: Try running the loop multiple times to get average.

like image 42
Zaheen Avatar answered Oct 11 '22 17:10

Zaheen