I'm trying to figure out how to write the most optimal if ... else if ... else ...
statement in C++
.
Suppose that we have 3 possible conditions based on some n
variable value: n = 0
, 0 < n < 100
, and n = 100
. Let's assume that n = 0
will occur in 1%
cases, 0 < n < 100
–90%
, and n = 100
–9%
. Note that if ... else if ... else ...
will be executed many times and the value of n
will be different each time.
My first assumption was to put conditions in the descending order (the most frequent – first, the least frequent – last) like below. However, the first condition will have 3 boolean expressions. And since the first condition will be always executed (in 100%
cases) and it consists of 3 boolean expressions (>
, <
, and &&
), those 3 expressions will be executed in 100%
cases. (Maybe there will be some optimization made by a compiler, and it will somehow be reduced to 2 expressions.) The second condition will be executed in 10%
cases and the third condition – in 1%
cases.
So, given that there will be a 1 000
iterations, there will be 3 100
boolean expressions evaluated (3 000 + 100
).
if ((n > 0) && (n < 100)) { // 3 boolean expressions will be executed in 100% cases. ...} else if (n == 100) { // 1 additional boolean expression – in 10% cases. ...} else { // n = 0 // No additional boolean expressions – in 1% cases. ...}
If to change the order of conditions (so that to eliminate the condition with 3 boolean expressions), there will be 1 910
boolean expressions evaluated (1 000 + 910
).
if (n == 100) { // 1 boolean expression will be executed in 100% cases. ...} else if (n == 0) { // 1 additional boolean expression – in 91% cases. ...} else { // 0 < n < 100 // No additional boolean expressions – in 90% cases. ...}
Do I understand it right? If no, how to properly optimize the code with if ... else if ... else ...
for speed?
Update: Based on the comments, did a test. The first variant gives less lines of the compiled code than the second one. Don't know Assembly language, so I'm not sure whether less lines is better in this case.