Are ternary statements faster than if/then/else st

2019-04-29 01:47发布

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?

4条回答
劫难
2楼-- · 2019-04-29 02:16

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.)

查看更多
戒情不戒烟
3楼-- · 2019-04-29 02:32

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.

查看更多
唯我独甜
4楼-- · 2019-04-29 02:37

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.

查看更多
该账号已被封号
5楼-- · 2019-04-29 02:39

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.

查看更多
登录 后发表回答