在 Visual C++ 中 switch 是如何编译的,它的优化和速度如何? [英] How does switch compile in Visual C++ and how optimized and fast is it?

查看:29
本文介绍了在 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).

这篇关于在 Visual C++ 中 switch 是如何编译的,它的优化和速度如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆