How does switch compile in Visual C++ and how optimized and fast is it?

ekul picture ekul · Apr 8, 2010 · Viewed 11.4k times · Source

As I found out that I can use only numerical values in C++'s switch statements, I thought that there then must be some deeper difference between it and a bunch of if-else's.

Therefore I asked myself:

  • (How) does switch differ from if-elseif-elseif in terms of runtime speed, compile time optimization and general compilation? I'm mainly speaking of MSVC here.

Answer

UncleBens picture UncleBens · Apr 8, 2010

A switch is often compiled to a jump-table (one comparison to find out which code to run), or if that is not possible, the compiler may still reorder the comparisons, so as to perform a binary search among the values (log N comparisons). An if-else chain is a linear search (although, I suppose, if all the relevant values are compile-time integral constants, the compiler could in principle perform similar optimizations).