I did the due-diligence to see if this has been asked before and didn't find anything identical but close, so here goes.
Say I have a chain of if-else-if statements.
foreach (value in valueList)
if (value == 120) {
w = true;
} else if (value == 140) {
x = true;
} else if (value == 160) {
y = true;
} else if (value == 180) {
z = true;
}
}
Is there any advantage of changing the else-if chain to ternary expressions such as:
foreach (value in valueList) {
w = (value == 120) ? true : false;
x = (value == 140) ? true : false;
y = (value == 160) ? true : false;
z = (value == 180) ? true : false;
}
My first inclination is no. Because of the for
loop every assignment is made each time the loop happens. Whereas in the if-else-if chain, the assignment is made only once. But the comparisons are made more often (right?). Can anybody settle this for me?
I know a switch
would easily defeat the both in terms of performance. Can I base this question on the assumption that using switch
is not an option?
I guess another question inside this question would be what are the Big-O comparisons between the two?
Note that both solutions are very different. The first one only assigns true
to one of those four variables while the other one will overwrite whatever value all four of them had before.
That being said, using the ternary operator in the second code is really bad. You can just assign the result of the comparison directly:
w = value == 120;
x = value == 140;
y = value == 160;
z = value == 180;
Taking aside the semantics, this will also make it likely a bit more performant than a if/else structure. You might think that just running a single comparison will make it faster, so the first solution should be better, but in fact, branching can be slow. And since comparison operations are actually really fast, just assigning the result of a comparison four times is likely “faster”.
Note that none of this will actually have any real performance impact. Both is very low-level and it’s very likely that you have something else in your application’s code that is way slower, being a likelier bottle neck. So I wouldn’t stress about using one or another way for performance here; just choose what is semantically correct and then use whatever solution makes the semantics as clear as possible.
I know a switch would easily defeat the both in terms of performance.
A switch statement gives you the same effect as a chain of ifs and elses, so there isn’t really a difference here.
I guess another question inside this question would be what are the Big-O comparisons between the two?
Both is linear, as you just loop through the list. Every other difference is constant, so it doesn’t matter in Big-O notation.