#include
#include
#include
using namespace std;
class spender
{
public:
spender(string strfun) :strfun(strfun)
{
t1 = std::chrono::steady_clock::now();
}
~spender()
{
auto t2 = std::chrono::steady_clock::now();
double dr_ms = std::chrono::duration<double, std::milli>(t2 - t1).count();
printf("%s耗时:%.3fms\n", strfun.c_str(), dr_ms);
}
private:
decltype(std::chrono::steady_clock::now()) t1;
string strfun;
};
string Remove_Space1(string str)
{
string result;
for (int i = 0; i < str.length(); i++)
{
if (!isspace(str[i]))
{
result = result + str[i];
}
}
return result;
}
string Remove_Space2(string str)
{
string result;
for (int i = 0; i < str.length(); i++)
{
if (!isspace(str[i]))
{
result += str[i];
}
}
return result;
}
string Remove_Space3(string str)
{
string result;
result.reserve(str.length());
for (int i = 0; i < str.length(); i++)
{
if (!isspace(str[i]))
{
result += str[i];
}
}
return result;
}
string Remove_Space4(const string &str)
{
string result;
result.reserve(str.length());
for (int i = 0; i < str.length(); i++)
{
if (!isspace(str[i]))
{
result += str[i];
}
}
return result;
}
void main()
{
string s = "hello world,hello world,hello world,hello world,hello world,\
hello world,hello world,hello world,hello world,hello world,hello world,hello world,hello world,hello world!";
{
spender t("Remove_Space1");
string strtmp = Remove_Space1(s);
printf("%s\n",strtmp.c_str());
}
{
spender t("Remove_Space2");
string strtmp = Remove_Space2(s);
printf("%s\n", strtmp.c_str());
}
{
spender t("Remove_Space3");
string strtmp = Remove_Space3(s);
printf("%s\n", strtmp.c_str());
}
{
spender t("Remove_Space4");
string strtmp = Remove_Space4(s);
printf("%s\n", strtmp.c_str());
}
system("pause");
}
结果:
从运行结果可以看出第一种方式最耗时,至于它的原因:result = result + str[i];是对象的拷贝而非移动,导致反复分配,释放内存和无畏地进行字符串复制。