ConcatB has 1 temp string, while ConcatA has 2 temp strings, thus ConcatB is twice faster.
$ cat cata.cpp
#include <string>
#include <iostream>
std::string ConcatA(const std::string& a, const std::string& b, const std::string& c)
{
return a + b + c;
}
int main(){
std::string aa="aa";
std::string bb="bb";
std::string cc="cc";
int count = 0;
for(int ii = 0; ii < 10000000; ++ii) {
count += ConcatA(aa, bb, cc).size();
}
std::cout<< count <<std::endl;
}
$ cat catb.cpp
#include <string>
#include <iostream>
std::string ConcatB(const std::string& a, const std::string& b, const std::string& c)
{
std::string r = a;
r += b;
r += c;
return r;
}
int main(){
std::string aa="aa";
std::string bb="bb";
std::string cc="cc";
int count = 0;
for(int ii = 0; ii < 10000000; ++ii) {
count += ConcatB(aa, bb, cc).size();
}
std::cout<< count <<std::endl;
}
$ clang++ -v
Apple LLVM version 5.0 (clang-500.2.79) (based on LLVM 3.3svn)
Target: x86_64-apple-darwin13.1.0
Thread model: posix
$ clang++ cata.cpp
$ time ./a.out
60000000
real 0m1.122s
user 0m1.118s
sys 0m0.003s
$ clang++ catb.cpp
$ time ./a.out
60000000
real 0m0.599s
user 0m0.596s
sys 0m0.002s
$