This question is more of a theoretical one than a practical one, considering only the performance of multiple if
vs. chained if else
. Lets leave aside switch
, readability, micro-optimizations, error-reducibility, etc.
Let's say I have the following construct:
if( i == 1 ){
// Do one thing
}
else if( i == 2 ){
// Do another thing
}
else if( i == 3 ){
// Do a third thing
}
// ... and so on
I've always assumed that would be more efficient to execute than the following:
if( i == 1 ){
// Do one thing
}
if( i == 2 ){
// Do another thing
}
if( i == 3 ){
// Do a third thing
}
// ... and so on
But is this really so in modern compilers? From what I understand, there are a lot of optimizations and branching strategies that compilers nowadays use on these types of constructs, so perhaps they both actually result in the same executable code?