C++ 超短字符串比较

     最近这几天的工作中用到了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

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值