C++: Performance of Switch Statement vs Lookup tables

Viewed 2893

I tried to compare the performance of switch statement and lookup tables as below.

This is the code using switch statement

#include <stdio.h>

int main()
{
    int n = 3;

    for (long i = 0; i < 10000000; ++i) {  
        switch (n) {
        case 0:
            printf("Alpha");
            break;
        case 1:
            printf("Beta");
            break;
        case 2:
            printf("Gamma");
            break;
        case 3:
            printf("Delta");
            break;
        default:
            break;
        }
    }

    return 0;
}

And here is the code using lookup tables:

#include <stdio.h>

static char const * const Greek[4] = {
  "Alpha",
  "Beta",
  "Gamma",
  "Delta"
};

int main()
{
    int n = 3;

    for (long i = 0; i < 10000000; ++i) {  
        if (n >= 0 && n < 4) {
            printf(Greek[n]);
        }
    }

    return 0;
}

I run two program on ubuntu 14.04, gcc version 4.8.4, using perf version 4.4.13 to analyze performance. And result:

  • Switch Statement: 6.764077822 seconds
  • Lookup tables: 6.665140483 seconds

I don't know why Switch Statement run slower than Lookup tables. As I known, Switch Statement using jump table, i think it should run faster than Lookup tables in my program (it has additional if statement).

2 Answers
Related