This is the mail archive of the
gcc@gcc.gnu.org
mailing list for the GCC project.
Re: Advantage of switch-case
- From: Joe Buck <Joe dot Buck at synopsys dot COM>
- To: Shameem Ahamed <shameem dot ahamed at hotmail dot com>
- Cc: "gcc at gcc dot gnu dot org" <gcc at gcc dot gnu dot org>
- Date: Thu, 16 Apr 2009 22:12:10 -0700
- Subject: Re: Advantage of switch-case
- References: <BLU149-W57E332F717DBE65BFCDF799F7B0@phx.gbl>
On Thu, Apr 16, 2009 at 09:07:58PM -0700, Shameem Ahamed wrote:
> Is there any advantage of using switch-case over if-else. I mean any internal optimizations, gcc can do on a Linux i386 machine?.
The optimizations in question are architecture-independent, though there
would undoubtedly be processor-specific weights.
Given a switch statement, gcc will generate either a balanced binary
tree or a jump table, depending on the number of branches and their
density. It has some freedom to optimize this structure that it might
not have for an if-then-else structure. But I think that the difference
is only going to be significant for a large switch (with many branches);
if there are few branches, the jump table won't be a win (so won't be
chosen), and the balanced tree would be about the same as what you would
write.
I would say that if a switch statement is a natural way to code something,
it would be wise to prefer it to if-then-else if there are four or more
branches (I admit I have no hard justification for the "four" here);
for fewer I'd make the decision based on clarity and maintainability.
Switch statements also give compilers more freedom to rearrange based on
profile-directed optimization. There was a GCC Summit paper on improving
GCC's code generation for switch statements, see
http://ols.fedoraproject.org/GCC/Reprints-2006/wienskoski-reprint.pdf
I don't know how much of that work got into the compiler, probably
it isn't in the 4.2.x version we're using now.