問題描述
對于 30 個 unsigned
枚舉使用 switch
語句與使用 if
語句的最佳實踐是什么,其中大約 10 個具有預(yù)期操作(目前是相同的操作).需要考慮性能和空間,但不是關(guān)鍵.我已經(jīng)抽象了代碼片段,所以不要因為命名約定而討厭我.
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();
}
推薦答案
使用開關(guān).
在最壞的情況下,編譯器將生成與 if-else 鏈相同的代碼,因此您不會丟失任何內(nèi)容.如果有疑問,請將最常見的情況放在 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.
在最好的情況下,優(yōu)化器可能會找到一種更好的方式來生成代碼.編譯器通常做的事情是構(gòu)建一個二叉決策樹(在一般情況下保存比較和跳轉(zhuǎn))或簡單地構(gòu)建一個跳轉(zhuǎn)表(根本不需要比較).
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).
這篇關(guān)于切換 if-else 語句的優(yōu)點的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!