我发现与老式的空字符结尾字符串相比,std::string
非常慢,甚至会使我的整个程序速度减慢2倍。
我本来以为STL会慢一些,但我没有想到会慢这么多。
我正在使用Visual Studio 2008的发布模式。它显示字符串赋值比char*
赋值慢100-1000倍(很难测试char*
赋值的运行时间)。我知道这不是公平的比较,一个指针赋值和一个字符串复制,但我的程序有很多字符串赋值,我不确定是否可以在所有地方使用“const reference”技巧。如果使用引用计数实现,我的程序就没问题了,但似乎现在不存在这样的实现了。
我的真正问题是:为什么现在没有人再使用引用计数实现,这是否意味着我们都需要更加谨慎地避免std::string常见的性能陷阱?
我的完整代码如下。
#include <string>
#include <iostream>
#include <time.h>
using std::cout;
void stop()
{
}
int main(int argc, char* argv[])
{
#define LIMIT 100000000
clock_t start;
std::string foo1 = "Hello there buddy";
std::string foo2 = "Hello there buddy, yeah you too";
std::string f;
start = clock();
for (int i=0; i < LIMIT; i++) {
stop();
f = foo1;
foo1 = foo2;
foo2 = f;
}
double stl = double(clock() - start) / CLOCKS\_PER\_SEC;
start = clock();
for (int i=0; i < LIMIT; i++) {
stop();
}
double emptyLoop = double(clock() - start) / CLOCKS_PER_SEC;
char* goo1 = "Hello there buddy";
char* goo2 = "Hello there buddy, yeah you too";
char *g;
start = clock();
for (int i=0; i < LIMIT; i++) {
stop();
g = goo1;
goo1 = goo2;
goo2 = g;
}
double charLoop = double(clock() - start) / CLOCKS_PER_SEC;
cout << "Empty loop = " << emptyLoop << "\n";
cout << "char* loop = " << charLoop << "\n";
cout << "std::string = " << stl << "\n";
cout << "slowdown = " << (stl - emptyLoop) / (charLoop - emptyLoop) << "\n";
std::string wait;
std::cin >> wait;
return 0;
}