Is there any (possible) performance difference between following switch statements or they are completely equivalent?
I've not found any significative difference when profiling them, but I'm still curious if any compiler/flag may improve it if using one or another.
// f, g, h can be functions such as int f(int)
int choose1(int x) {
switch (x) {
case 0: return f(x);
case 2: return g(x);
case 5: return h(x);
}
return x;
}
int choose2(int x) {
switch (x) {
case 0: return f(x);
case 2: return g(x);
case 5: return h(x);
default: return x;
}
}
What about if case statements are not so simple, like:
int choose3(int x) {
switch (x) {
case 0: /* some actions1 */; return f(x);
case 2: /* some actions2 */; return g(x);
case 5: /* some actions3 */; return h(x);
}
/* more actions */
return x;
}
int choose4(int x) {
switch (x) {
case 0: /* some actions1 */; return f(x);
case 2: /* some actions2 */; return g(x);
case 5: /* some actions3 */; return h(x);
default: /* more actions */; return x;
}
}
Even when searched around for a while I've only found posts related to the single exit-point (very common in C) or just talking about programming practices (maintenance, readability...). A similar question is this one related to the if statement, but all answers basically end discussing early return convenience (programming practice) rather than actual performance differences.
I'm not interested now in such programming practices, although I'll be glad to know your contributions in comments.