Kai*_*aan 5 c++ optimization if-statement switch-statement
我有一个问题,关于是否在一个被调用很多的函数中使用'case'或'ifs'.现在是'ifs'中的以下内容; 代码不言自明:
int identifyMsg(char* textbuff) {
if (!strcmp(textbuff,"text")) {
return 1;
}
if (!strcmp(textbuff,"name")) {
return 2;
}
if (!strcmp(textbuff,"list")) {
return 3;
}
if (!strcmp(textbuff,"remv")) {
return 4;
}
if (!strcmp(textbuff,"ipad")) {
return 5;
}
if (!strcmp(textbuff,"iprm")) {
return 6;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我的问题是:开关性能会更好吗?我知道如果使用'ifs',我可以将最有可能的选项放在顶部.
Mar*_*lon 11
您不能switch对字符串使用语句,因为它们是指针,在编译时不会进行评估.你很难使用一堆if语句.
然而,出于性能的考虑,我认为当有更多的条件要检查时,开关的性能会更好,但差异将是如此微小,无关紧要.
我以前从未测试过这个,但我已经读过这种开关优化:
switch (value) {
case frequent_value1:
case frequent_value2:
case frequent_value3:
break;
default:
switch (value) {
case infrequent_value1:
case infrequent_value2:
case infrequent_value3:
break;
}
}
Run Code Online (Sandbox Code Playgroud)
您可以使用gperf生成你想看到的"动词"的完美哈希.然后你可以使用一个switch声明.
或者,你可以做这样的事情:
switch (textbuff[0])
{
case 'i':
{
switch (textbuff[1])
{
case 'p':
{
switch (textbuff[2])
{
case 'a': /* something. */ break;
case 'r': /* something else. */ break;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
(你明白了).
作为另一种选择(如果所有命令都是4个字符),将它们转换为一个32位数字,然后打开它:
int32_t mashed =
textbuff[0] << 24 |
textbuff[1] << 16 |
textbuff[2] << 8 |
textbuff[3];
switch (mashed) { /* ... */ }
Run Code Online (Sandbox Code Playgroud)
但说实话,除非选项列表特别大,否则这个功能被称为淫秽次数,这是不值得的.
记住:先测量; 稍后优化(仅在必要时).