在 Visual C++ 中 switch 是如何编译的,它的优化和速度如何?

当我发现我只能在 C++ 的 switch 语句中使用数值时,我认为它与一堆 if-else的.

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.

因此我问自己:

  • (如何)switchif-elseif-elseif 在运行速度、编译时间优化和一般编译方面有何不同?我在这里主要说的是 MSVC.
  • (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.

推荐答案

一个开关经常被编译成一个跳转表(一个比较来找出要运行的代码),或者如果这不可能,编译器可能仍然对比较重新排序,以便在值之间执行二分搜索(log N 比较).if-else 链是线性搜索(尽管我想,如果所有相关值都是编译时积分常量,编译器原则上可以执行类似的优化).

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).

相关文章