Sid*_*427 2 c string performance if-statement
我在C中编写了一个小文本匹配程序,它基本上检查某些字符串中是否存在少量字符(以char数组的形式).它现在正在工作,我有一个像这样的代码块:
if (c == 'A') return 1;
else if (c == 'B') return 1;
else if (c == 'C') return 1;
....
....
else if (c == 'Z') return 1;
else return 0;
Run Code Online (Sandbox Code Playgroud)
上面的块是否更快?或者这会更快?
if (c == 'A' || c == 'B' || c == 'C' ||....|| c == 'Z') return 1;
else return 0;
Run Code Online (Sandbox Code Playgroud)
快速,我的意思是字面上快,即如果我从程序的开始直到结束运行一个简单的计时器,这可能会缩短执行时间?
我建议你做以下事情:
#include <ctype.h>
...
return isupper(c)
Run Code Online (Sandbox Code Playgroud)
而不是手动检查所有这些.标准C库函数速度相当快,因此性能应该是可以接受的.
经验法则是,如果您不确定它是否真的值得,您不应该担心这些小的性能问题.
在任何情况下,如果你想要检查任何AZ字母,那么(请注意,这假设所使用的字符的编码不应该有任何外部符号A
和Z
或者这不起作用)
if (c >= 'A' && c <= 'Z')
Run Code Online (Sandbox Code Playgroud)
肯定是一种更简单的方法.
不要忘记,对于表达式值的长链接,你甚至可以使用switch
语句:
switch (exp) {
case 'A':
case 'B':
case 'C':
...
return 1;
default: return 0;
}
Run Code Online (Sandbox Code Playgroud)
switch
在某些情况下,A 可能稍微快一些,因为根据编译器,它可以使用查找表,但我们实际上是在谈论微秒.
为了完整起见,C标准库有两个方法isupper
和isaplha
可用于:
if (isupper(c)) // c is an alphabetic uppercase character
Run Code Online (Sandbox Code Playgroud)