我有同样的疑问,所以我做了一个小测试来检查这个(g++ 4.8.5 with C++11 profile on Linux, Intel, 64 bit under VmWare Fusion)。
结果很有趣:
推:19
附加:21
++++:34
这可能是因为字符串长度(大),但是与 push_back 和 append 相比,运算符 + 非常昂贵。
另外有趣的是,当操作符只接收一个字符(不是字符串)时,它的行为与 push_back 非常相似。
为了不依赖于预先分配的变量,每个循环都定义在不同的范围内。
注意:vCounter 只是使用 gettimeofday 来比较差异。
TimeCounter vCounter;
{
string vTest;
vCounter.start();
for (int vIdx=0;vIdx<1000000;vIdx++) {
vTest.push_back('a');
vTest.push_back('b');
vTest.push_back('c');
}
vCounter.stop();
cout << "push :" << vCounter.elapsed() << endl;
}
{
string vTest;
vCounter.start();
for (int vIdx=0;vIdx<1000000;vIdx++) {
vTest.append("abc");
}
vCounter.stop();
cout << "append :" << vCounter.elapsed() << endl;
}
{
string vTest;
vCounter.start();
for (int vIdx=0;vIdx<1000000;vIdx++) {
vTest += 'a';
vTest += 'b';
vTest += 'c';
}
vCounter.stop();
cout << "++++ :" << vCounter.elapsed() << endl;
}