切换if-else语句的优点 [英] Advantage of switch over if-else statement
问题描述
使用开关
语句与使用如果
语句for 30 unsigned
枚举,其中约10个具有预期操作(当前是相同的操作)。性能和空间需要考虑,但不是关键。
switch
语句:
// numError是一个错误枚举类型,0是无错误的情况
// fire_special_event stub方法用于共享处理
switch(numError)
{
case ERROR_01:// intentional fall-through
case ERROR_07:// intentionally fall-through
case ERROR_0A:// intentional fall-through
case ERROR_10:// intentional fall-through
case ERROR_15:// intentional fall-through
case ERROR_16:// intentionally fall-通过
case ERROR_20:
{
fire_special_event();
}
break;
默认值:
{
//无需额外操作的错误代码
}
break;
}
if
if((ERROR_01 == numError)||
(ERROR_07 == numError)||
(ERROR_0A == numError)||
(ERROR_10 == numError)||
(ERROR_15 == numError)||
(ERROR_16 == numError)||
(ERROR_20 == numError))
{
fire_special_event();
}
使用开关。 >
在最坏的情况下,编译器将生成与if-else链相同的代码,所以你不会丢失任何东西。如果有疑问,最常见的情况首先进入switch语句。
在最好的情况下,优化器可能会找到一个更好的方法来生成代码。编译器所做的常见事情是构建一个二进制决策树(在平均情况下保存比较和跳转),或者只是构建一个跳转表(根本没有比较)。
What's the best practice for using a switch
statement vs using an if
statement for 30 unsigned
enumerations where about 10 have an expected action (that presently is the same action). Performance and space need to be considered but are not critical. I've abstracted the snippet so don't hate me for the naming conventions.
switch
statement:
// numError is an error enumeration type, with 0 being the non-error case
// fire_special_event() is a stub method for the shared processing
switch (numError)
{
case ERROR_01 : // intentional fall-through
case ERROR_07 : // intentional fall-through
case ERROR_0A : // intentional fall-through
case ERROR_10 : // intentional fall-through
case ERROR_15 : // intentional fall-through
case ERROR_16 : // intentional fall-through
case ERROR_20 :
{
fire_special_event();
}
break;
default:
{
// error codes that require no additional action
}
break;
}
if
statement:
if ((ERROR_01 == numError) ||
(ERROR_07 == numError) ||
(ERROR_0A == numError) ||
(ERROR_10 == numError) ||
(ERROR_15 == numError) ||
(ERROR_16 == numError) ||
(ERROR_20 == numError))
{
fire_special_event();
}
Use switch.
In the worst case the compiler will generate the same code as a if-else chain, so you don't lose anything. If in doubt put the most common cases first into the switch statement.
In the best case the optimizer may find a better way to generate the code. Common things a compiler does is to build a binary decision tree (saves compares and jumps in the average case) or simply build a jump-table (works without compares at all).
这篇关于切换if-else语句的优点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!