一般情况下,清空字符串有两种方式:(1)给字符串赋值空串。(2)调用std::string::clear()函数。
测试代码:
const int kMaxLoop = 1000000;
{
boost::timer::auto_cpu_timer timer;
std::string test;
int i = kMaxLoop;
while (i--) {
test = "11";
test = "";
}
}
{
boost::timer::auto_cpu_timer timer;
std::string test;
int i = kMaxLoop;
while (i--) {
test = "11";
test.clear();
}
}
测试结果:
0.691557s wall, 0.687500s user + 0.000000s system = 0.687500s CPU (99.4%)
0.554783s wall, 0.562500s user + 0.000000s system = 0.562500s CPU (101.4%)
测试结论: 尽可能用std::string::clear()清空字符串。