Optional else statements: Is there a downside to using ELSE IF when only IF can be used?
Consider the speed of the following examples (please ignore that this example is completely ridiculous):
int multiply(int a, int b) {
if (a == 0 || b == 0) {
return 0;
}
if (a == b) {
return pow(a, 2);
}
return a*b;
}
against
int multiply(int a, int b) {
if (a == 0 || b == 0) {
return 0;
} else if (a == b) {
return pow(a, 2);
} else {
return a*b;
}
}
Obviously this is not really needed here, but when I work with complex operations I find it much easier to read when formatting the latter. Does it take longer to start in the second configuration? Will I sacrifice anything?
source to share
EDIT: Please answer the OP's question first and then talk about the general case.
Sepcific-to-your-problem Answer: In your case, since you have a return, on every condition it will break out of flow control. In general, their chains are better, if necessary.
General answer: Yes, in fact, if you only use if your program checks all conditions, even if one of them was met.
When executing the chain if, else-if, else, after one of the conditions is met, all others in this chain will be ignored.
source to share
In this particular case, no compiler that I know of could generate an exact result for both. However, in a general case:
- Writing for easy reading and maintenance
- Profile Profile Profile
- Optimize only where you find bottlenecks
- Test your optimization using more profiling
The fourth part is important, the hardware has a lot of awesome optimizations built in, it's not at all intuitive which is Faster.
source to share