3 ms·
Or just don't use switch. If it's a small expression, an if/else chain takes no more lines of code and is not less efficient. If it's a large expression, it m
by ajross 15y ago
Or just don't use switch. If it's a small expression, an if/else chain takes no more lines of code and is not less efficient. If it's a large expression, it might be better expressed with a function pointer table.
I'm not a zealot on this stuff, and write switch statements regularly (though I do strongly prefer if chains for most stuff) but if you're really hitting this regularly I think a change in process might be in order.
- DHowett 15y agoIt can be slightly less efficient when (on supporting architectures) the compiler could automatically generate a jump table in place of stacked conditionals, which it cannot do for a chain of ifs.
- ajross 15y agoThis is a myth that won't die. Jump tables can't be branch predicted, so they're generally significantly slower unless the number of cases is very high. And it's not true that the compiler "cannot" emit a jump table for an if chain anyway. A bunch of if/else-if expressions of the form "some_var == constant" can certainly be detected (though again, it probably isn't).
- klez 15y agoUnfortunately, I'm not able to decide to do this. Most of our code is machine-generated, and our boss doesn't want to touch the generator in general.