Re: How do Visual C++ compiler optimize switch & cases?

Tech-Archive recommends: Repair Windows Errors & Optimize Windows Performance



He Shiming wrote:
> Hi,
>
> I have this switch block in my program, and it has over 200 cases. I'm
> wondering if I should worry about its performance. Is iterating over
> all the case labels a time-consuming job?
>
> I know from others that if the compiler is "smart enough", it could
> sort the case labels to make label-addressing faster. Is that what
> Visual C++ compiler has been doing? In general, do I need to worry
> about the performance of such structured code?

In an optimized build, VC++ will generate a mixture of up to three different
techniques:

1. Sequential if/else logic (for switches with very few cases - e.g. 2).

2. Table lookup (for switches with one or more ranges of consequtive case
values).

3. Tree search (optimized if/else by sorting the tags and then generating a
binary search of the tag space).

The compiler will mix these techniques: a switch with mixed labels and
contiguous ranges will typically use the binary tree logic to select from
indivudal cases or table-based dispatch.

-cd


.



Relevant Pages

  • Re: Just curiosity about some constructs
    ... and sometimes people wanted to give the compiler hints ... This is about the switch statement. ... A whilewill execute the statement after the ... with labels and goto (although case labels are a little different ...
    (comp.lang.c)
  • Re: Banks and economy
    ... so I switched to working on a C compiler. ... I've found I keep using C99 features or limits, e.g., quantity of switch ... if you massively exceed the minimum required number of labels in a switch ...
    (alt.lang.asm)
  • Re: optimizing the switch statement in Duffs Device (casting a label, label abuse)
    ... The switch itself scales horribly. ... Can we get a label's address and subtract an integer to it? ... What if the compiler thinks it's "clever":)? ... What you seek can be done with gcc, using the labels as values ...
    (comp.lang.c)
  • Re: 8051 and a C switch statement
    ... I'm using the rasionance C compiler. ... The C standard requires that the implementation support at ... least 257 labels in a switch statement. ... least one program containing 257 case labels. ...
    (comp.arch.embedded)
  • Re: DPROD issues
    ... a switch like that typically ... makes a compiler nonstandard in that mode. ... treatment of specific intrinsics is one ... subroutine sub1a ...
    (comp.lang.fortran)