C++的string逐位处理效率比较

 

今天看到一个对string做逐位处理的代码,我看见代码使用指针来指向string,我就在想为什么不用中括号,型如string s; s[i] = ....; 这种操作。

 

想到这个代码作者一向以效率优先考虑,于是我测试了一下效率,果不其然。。。哈哈

 

#include <iostream>
#include <string>
#include <cstdlib>
#include <cstdio>
#include <stdlib.h>
#include <stdio.h>
#include <sys/time.h>
using namespace std;

static unsigned long GetTimeMicros()
{
    struct timeval tv;
    long time;
    gettimeofday(&tv, NULL);
    time = tv.tv_sec;
    return (((unsigned long)tv.tv_sec) * 1000000) + tv.tv_usec;
}


string forceLower(string astr) 
{
    char* str = const_cast<char*>(astr.c_str());
    for (size_t i = 0; i <= astr.size(); ++i)
    {
	if (str[i] >= 'A' && str[i] <= 'Z') 
	{
	    str[i] += 32;
	}
    }
    return astr;
}

string forceLower2(string astr)
{
    for (size_t i = 0; i < astr.size(); ++i)
    {
	if (astr[i] >= 'A' && astr[i] <= 'Z')
	{
	    astr[i] += 32;
	}
    }
    return astr;
}

int main()
{
    string s = "ASFOAiLJSLDJFLSDLKFKJSDLWJERA";

    int start, end;
    
    start = GetTimeMicros();
    for (int i = 0; i < 100000; i++)
    {
	forceLower(s);
    }
    end = GetTimeMicros();
    cout << "做10万次转小写操作(用指针),耗时(微秒): " << end - start << endl;


    start = GetTimeMicros();
    for (int i = 0; i < 100000; i++)
    {
	forceLower2(s);
    }
    end = GetTimeMicros();
    cout << "做10万次转小写操作(用中括号),耗时(微秒): " << end - start << endl;

    return 0;
}


 


输出:

做10万次转小写操作(用指针),耗时(微秒): 31013
做10万次转小写操作(用中括号),耗时(微秒): 81645


可以看出来,有效率是三倍的差距。在做高性能的程序,只有每个细节都全力保证高性能,才能为实现整体高性能添砖加瓦!!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值