考虑以下四种情况:
#include <string>
int main()
{
std::string s("Hi I'm Da");
1. s += "n";
2. s += 'n';
3. s = s + "n";
4. s = s + 'n';
return 0;
}
使用以下方法调用运行此测试套件:
g++ -std=c++11 -O3 -DVER=case -Wall -pedantic -pthread test.cpp -o test
使用 g++ 版本 4.8.3 20140624,我得到了以下结果:
2.16172ms
0.48296ms
510.202ms
510.455ms
现在我明白+=
更快的原因是因为在赋值之前不需要使用+
来复制,但是为什么情况1和2相比于情况3和4会表现出显著的差异呢?另外,使用双引号或单引号如何影响连接速度?
"n"
是C风格的字符串,而'n'
根本不是字符串,而是一个单个字符。难怪它们被处理为完全不同的代码分支,针对处理不同的一般情况进行了优化。 - AnT stands with Russiastd::basic_string
没有一个适用于原始字符串字面值的合适构造函数 (template<std::size_t N> basic_string( const char (&str[N]) )
)。字符串字面值的大小在编译时已知,但我们仍将它们视为愚蠢的以 null 结尾的 C 字符串。 - Manu343726