javascriptperformanceternary-operator

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?


Solution

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