https://gcc.gnu.org/bugzilla/show_bug.cgi?id=87925

            Bug ID: 87925
           Summary: Missed optimization: Single-value if-then-else chains
                    treated differently than switch'es
           Product: gcc
           Version: unknown
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: rtl-optimization
          Assignee: unassigned at gcc dot gnu.org
          Reporter: eyalroz at technion dot ac.il
  Target Milestone: ---

Have a look at this GodBolt example: https://gcc.godbolt.org/z/zR03rA

On one hand, we have:

    void foo(int i) {
        switch (i) {
            case 1: boo<1>(); break;
            case 2: boo<2>(); break;
            case 3: boo<3>(); break;
            case 4: boo<4>(); break;
            // etc. etc.
        }
    }

on the other hand we have the same, but using an if-then-else chain:

    void bar(int i) {
        if      (i == 1) boo<1>();
        else if (i == 2) boo<2>();
        else if (i == 3) boo<3>();
        else if (i == 4) boo<4>();
        // etc. etc.
    }

The switch statement gets a jump table; the if-then-else chain - does not. At
the link, there are 20 cases; g++ starts using a jump table with 4 switch
values.

This is not just a matter of programmers needing to remember to prefer switch
statements (which it's better not to require of them), but rather that
if-then-else chains are sometimes generated by expansion of templated code,
e.g. this example for checking for membership in a set of values (= all values
of an enum):

    https://stackoverflow.com/a/53191264/1593077

while switch() statements of variable do not get generated AFAICT. It would
thus be quite useful if such generated code would not result in
highly-inefficient long chains of comparisons.

Reply via email to