今天看到一个对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
可以看出来,有效率是三倍的差距。在做高性能的程序,只有每个细节都全力保证高性能,才能为实现整体高性能添砖加瓦!!