std::string各操作性能比较
测试程序
#include <sys/time.h>
#include <iostream>
#include <string>
int main()
{
struct timeval tv[2];
struct timezone tz;
int count = 50000;
int elapsed = 0;
// .. string initialization
gettimeofday(&tv[0], &tz);
while(count--) {
// .. real action here ..
}
gettimeofday(&tv[1], &tz);
elapsed = (tv[1].tv_sec - tv[0].tv_sec) * 1000000
+ (tv[1].tv_usec - tv[0].tv_usec);
std::cout << "elapsed: " << (double)elapsed / 1000 << "ms" << std::endl;
}
operator+ vs append
使用 s = “/” + t, 测试时间为 16.375ms, 但是使用 s.append(”/”).append(t) 时间是 5.528ms.
operator+ vs operator +=
使用 s = s + t, 测试时间为 5596.4ms, 而相比之下 s += t 需要 4.639ms.
结论
很明显,像书本上讲的一样,opterator + 总是会创建一个临时对象。所以,要慢很多。因此,当需要连接字符串时应该首选 ** += **.