You did not mention the 3rd alternative to not pre-distributing anything at all in the string and just let the optimizer do what is best.
Given these two functions, func1 and func3 :
void func1(const char* text) { std::string s; s.reserve(50); s += "com.domain.event."; s += text; std::cout << s; } void func3(const char* text) { std::string s; s += "com.domain.event."; s += text; std::cout << s; }
The example on http://goo.gl/m8h2Ks shows that the gcc assembly for func1 will only add an extra 3 to reserve space for 50 characters compared to when pre-allocation is not performed in func3. One of the calls is the row add call, which in turn will give some overhead:
leaq 16(%rsp), %rdi movl $50, %esi call std::basic_string<char>::append(char const*, unsigned long)
Looking only at the code, this does not guarantee that func3 is faster than func1, though, because it has fewer instructions. Cache and other things also contribute to actual performance, which can only be measured by measuring, as others have pointed out.
source share