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

I see a lot:

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

in javascript. It's faster than

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

Or is it written concisely for convenience?

+5
source share
4 answers

Please enjoy this - if the difference is statistically significant, it also matters (true or false) - obviously, these are just other things on the machine that affect browser performance:

Here's the link

different results!

There is a fundamental difference between the two, triple expressions are expressions, not a flow of control. If there is a case when someone writes this as a triple expression instead of the standard if / than / else, when both work the same way, they (in my opinion) make the code more difficult to read for no good reason.

. javascript. - .

+4

- . , , , .

( , , - ).

+2

statisitics: enter image description here

, (?:) , if/else.

+2

, .

, , ( if/else), , , - , , , 3 .

, , :

// declarations  
var num1 = 10, num2, i = 0, start, end;

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

for(i; i < 100000000; i++) {

  // first part if /else
  if(x == 10)
    y = x;
  else
    y = 0;

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

}

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

: ( ).

: , .

0

All Articles