0

I was wondering if below code has any difference between #1, #2 and #3 when passing a string to a function (eg. insert into a vector). Especially when dealing with millions of strings in the code.

std::vector<std::string> v;
std::string s("foo");
int i = 1;
v.push_back( s + "bar" + boost::lexical_cast<std::string>(i) );  // #1
v.push_back( std::string(s + "bar" + boost::lexical_cast<std::string>(i)) );  // #2
std::string s2 = s + "bar" + boost::lexical_cast<std::string>(i);
v.push_back(s2);  // #3
0

2 Answers 2

1

With a decent optimizer there should be no difference between #1 and #2, but #1 gives you the biggest chance that the compiler actually does temporary elimination.

However, #3 contains a named temporary, so it probably needs a great optimizer to detect that it's just that - a temporary.

Sign up to request clarification or add additional context in comments.

3 Comments

push_back takes T as const&. The compiler will be binding the temporary created by the expression or the one passed in as a variable. It won't make a bit of difference.
@CrazyEddie : In C++11 there's a big difference – #1 and #2 are rvalues and will be moved into the vector automatically, #3 would need to be moved explicitly.
What if I need to loop through these code million times, is there an efficient way to reuse the memory space for the temporary string? Just like the way C# does with StringBuilder class. It only creates once, and reuses the memory over and over again.
1

Probably not. They should be equivalent.

One way you could get performance gain though is by pre-allocating your string:

std::string s;
s.reserve(10); // or so...
s.append("foobar").append(lexical_cast<std::string>(i));

You probably would not gain enough performance here to make it worth the hassle though.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.