" std :: string"或“const std :: string&”论据? (参数在内部复制和修改) [英] "std::string" or "const std::string&" argument? (the argument is internally copied and modified)
本文介绍了" std :: string"或“const std :: string&”论据? (参数在内部复制和修改)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
请考虑以下代码:
void doSomethingWithString(string& mString)
{
// mString gets modified in here
}
string getCopy1(const string& mString)
{
string result{mString}; doSomethingWithString(result); return result;
}
string getCopy2(string mString)
{
doSomethingWithString(mString); return mString;
}
getCopy1
getCopy2
,什么:
- 清楚地显示传递的字符串不会
- 速度更快/可以通过编译器(C ++)更好地优化 11 enabled,consider move semantics)
- Clearly shows that the passed string isn't going to get modified
- Clearly shows that the user will get a new string returned
- Is faster / can be better optimized by the compiler (C++11 enabled, consider move semantics)
?
推荐答案
进行一些测试,使用G ++ 4.8.1在Linux Mint x64。
标志: -std = c ++ 11 -O3 -DNDEBUG
Ran some tests, with G++ 4.8.1 on Linux Mint x64.
Flags: -std=c++11 -O3 -DNDEBUG
void doSomethingWithString(string& mString) { mString[0] = 'f'; }
string getCopy1(const string& mString)
{
string result{mString}; doSomethingWithString(result); return result;
}
string getCopy2(string mString)
{
doSomethingWithString(mString); return mString;
}
int main()
{
string s{"132958fdgefi9obm3890g54"};
string t{""};
{
startBenchmark();
for(int i{0}; i < 20000000; ++i) t = getCopy1(s);
log(endBenchmark(), "getCopy1 variable");
}
{
startBenchmark();
for(int i{0}; i < 20000000; ++i) t = getCopy1("abcsd");
log(endBenchmark(), "getCopy1 literal");
}
{
startBenchmark();
for(int i{0}; i < 20000000; ++i) t = getCopy2(s);
log(endBenchmark(), "getCopy2 variable");
}
{
startBenchmark();
for(int i{0}; i < 20000000; ++i) t = getCopy2("abcsd");
log(endBenchmark(), "getCopy2 literal");
}
return 0;
}
输出:
[getCopy1 variable] 1236 ms
[getCopy1 literal] 1845 ms
[getCopy2 variable] 993 ms
[getCopy2 literal] 857 ms
结论:
getCopy2
更快,尤其是对于右值(字符串)。
getCopy2
is faster, especially with rvalues (literal strings).
这篇关于" std :: string"或“const std :: string&”论据? (参数在内部复制和修改)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文