#include <iostream>
//优化前函数 remove_ctrl
std::string remove_ctrl(std::string s) {
std::string result;
for(int i = 0;i < s.length();i++) {
if(s[i] >= 0x20)
result = result + s[i];
}
return result;
}
//优化后函数 remove_ctrl_opt
std::string remove_ctrl_opt(const std::string& src,std::string& dst) {
int n = src.size();
dst.reserve(n);
for(auto it = src.begin();it != src.end();it++) {
if(*it >= 0x20)
dst += *it;
}
return dst;
}
int main(){
std::string src = "hello,world,hello,world,hello,world,hello,world,hello,world,hello,world,hello,world,hello,world";
std::string result;
for(int i = 0;i < 1000000;i++)
std::string result = remove_ctrl(src);
for(int i = 0;i < 1000000;i++)
remove_ctrl_opt(src,result);
return 0;
}
优化函数,从参数拷贝,string 提前 reserve,减少临时变量,结果分别循环 1000000 次,使用 time ./a.out 测试执行时间,优化后的耗时反而很高(优化前 6s 左右,优化后 60s 没执行完直接 control+c 了)。
排查原因,发现将函数 remove_ctrl_opt 的返回类型修改为 void,函数体 return;优化后耗时提升 6 倍左右。 这到底是什么原因? return string ,难道开销这么大?但是优化前函数也是这样,执行才 6s 。