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?
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?
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:
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.
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.)
if (condition) { return x; } else { return 0; }
vs return condition ? x : 0;
–
Brannen int finalStatus = condition ? x : 0; return finalStatus;
This code is clear -- here is the line where I calculate the final status. I'm going to return the final status. When the way to calculate the final status changes you change the line that calculates it. you don't have change other parts. If you are returning something other that final status then you should use a name that reflects what you are doing. –
Bacteriology condition | 0
but only if condition is a number and greater than zero. Also works if condition is undefined, or null in JavaScript I think. very useful for efficiently turning undefined or null into 0 to prevent NullPointerException etc. wait thats JAva nvm –
Brannen Here is the statisitics:
After multiple tests and observations, it can be concluded,that the most cases the ternary operator(?:
) is slower,than if/else
.
if/else
wins the race. –
Proportional if/else
wins.Compare flow false
with tri false
, and flow true
with tri true
. –
Proportional ?:
and if/else
are syntax. What matters is implementation. It's not all that good to draw such an absolute conclusion from one test, tested in one browser. –
Willodeanwilloughby 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.
I modified this test that Zaheen made to make it run the test 50 times on both if...else and ternary and automatically output a list of the results and averages of each one into the console, and it consistently gives me a slightly faster speed for the ternary than the if...else when I run it in the console in Microsoft Edge.
var lista = []
var listb = []
var ib = 0
var ic = 0
for(; ib < 50; ib++) {
// 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)
lista.push(endTime)
}
for(; ic < 50; ic++) {
// 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)
listb.push(endTime)
}
var averagea = 0
lista.forEach(v=>averagea+=v)
averagea/=lista.length
var averageb = 0
listb.forEach(v=>averageb+=v)
averageb/=listb.length
console.log({ifelse: {times: lista, average: averagea+" ms"}, ternary: {times: listb, average: averageb+" ms"}})
Here are the results that I got from the console in Microsoft Edge:
{
"ifelse": {
"times": [
166,
143,
148,
161,
151,
138,
135,
148,
150,
154,
150,
148,
143,
140,
150,
141,
157,
140,
150,
152,
185,
223,
198,
160,
147,
144,
156,
173,
154,
170,
152,
165,
150,
150,
147,
146,
136,
146,
147,
146,
143,
146,
140,
141,
153,
147,
143,
136,
146,
156
],
"average": "152.22 ms"
},
"ternary": {
"times": [
144,
148,
159,
139,
138,
144,
143,
148,
137,
142,
152,
147,
147,
157,
146,
141,
144,
142,
150,
135,
147,
149,
144,
139,
156,
138,
144,
148,
142,
143,
142,
141,
146,
143,
142,
143,
140,
137,
139,
149,
144,
137,
139,
153,
138,
140,
149,
151,
141,
139
],
"average": "144.12 ms"
}
}
© 2022 - 2024 — McMap. All rights reserved.