最近这几天的工作中用到了C++字符串比较。在一次运行中需要做海量的字符串相等的比较。而且字符串都是3-5字节长度的字符串,在这里在占用了太多的CPU资源。
如何快速比较短字符串,这里也是有方法的。(学习了nginx字符串比较)
首先思路转化,字符串比较在CPU指令中是逐字节比较,比如有”abc”和“abd”这两个字符串做是否相同的比较。需要执行三次一字节的比较指令。而4(8)字节整数类型的比较则只需要一次CPU指令就可以完成。
我们需要把3字节的字符串转换成4字节的整型做比较就会提高比较速率。
如何做转换呢?可以利用C语言的强制类型转换命令让计算机帮我们完成转换任务。好了废话不多说了,对于程序员还是直接上代码看的清晰。
main.cpp
#include <iostream>
#include <string>
using namespace std;
int main(int argc, char **argv)
{
char code[] = "200";
string strcode("200");
cout<<(int)*(int*)"200" <<"\n" << (int)*(int*)code << endl;
if( (int)*(int*)"200" == (int)*(int*)code )
cout<<"相等\n";
string ret = ( (int)*(int*)"200" == (int)*(int*)code ? "相等" : "不相等" );
ret = ( (int)*(int*)"200" == (int)*(int*)strcode.c_str() ? "相等" : "不相等" );
cout << ret << endl;
return 0;
}
编译
g++ -o main main.cpp
执行
./main
3158066
3158066
相等
相等
测试
#include <iostream>
#include <string>
using namespace std;
int main(int argc, char **argv)
{
string strcode("200");
string strcode2("200");
int i = 1000*1000*1000;
while(i--)
{
//((int)*(int*)"200" == (int)*(int*)strcode.c_str() ? "相等" : "不相等" );
(strcode == strcode2 ? "相等" : "不相等" );
}
return 0;
}
系统环境
Ubuntu 14.04
Intel(R) Core(TM) i7-2670QM CPU @ 2.20GHz
Intel(R) Core(TM) i7-2670QM CPU @ 2.20GHz
Intel(R) Core(TM) i7-2670QM CPU @ 2.20GHz
Intel(R) Core(TM) i7-2670QM CPU @ 2.20GHz
Intel(R) Core(TM) i7-2670QM CPU @ 2.20GHz
Intel(R) Core(TM) i7-2670QM CPU @ 2.20GHz
Intel(R) Core(TM) i7-2670QM CPU @ 2.20GHz
Intel(R) Core(TM) i7-2670QM CPU @ 2.20GHz
time ./main
real 0m3.328s
user0m3.328s
sys 0m0.000s
time ./main
real 0m22.513s
user0m22.536s
sys 0m0.000s