切换 if-else 语句的优点

Advantage of switch over if-else statement(切换 if-else 语句的优点)
本文介绍了切换 if-else 语句的优点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

对于 30 个 unsigned 枚举使用 switch 语句与使用 if 语句的最佳实践是什么,其中大约 10 个具有预期操作(目前是相同的操作).需要考虑性能和空间,但不是关键.我已经抽象了代码片段,所以不要因为命名约定而讨厌我.

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 语句:

// 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 语句:

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 语句中.

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 语句的优点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

What do compilers do with compile-time branching?(编译器如何处理编译时分支?)
Can I use if (pointer) instead of if (pointer != NULL)?(我可以使用 if (pointer) 而不是 if (pointer != NULL) 吗?)
Checking for NULL pointer in C/C++(在 C/C++ 中检查空指针)
Math-like chaining of the comparison operator - as in, quot;if ( (5lt;jlt;=1) )quot;(比较运算符的数学式链接-如“if((5<j<=1)))
Difference between quot;if constexpr()quot; Vs quot;if()quot;(“if constexpr()之间的区别与“if())
C++, variable declaration in #39;if#39; expression(C++,if 表达式中的变量声明)