I wonder to learn how costly is the memory allocation process in a utility function. For example is there a big difference between the following implementations?
string method_A (string inp) {
auto num_fillers = inp.length() - 4;
string filler(num_fillers, '-');
string res = filler + inp.substr(num_fillers);
return res;
}
string method_B (string inp) {
const int expect_len =4;
auto num_fillers = inp.length() - expect_len;
string res;
res.reserve(num_fillers + expect_len);
res.assign(num_fillers, '-');
res+= inp.substr(num_fillers);
return res;
}
Is there any benefit of using method_B instead of method_A? What are the Pros and cons of each?
Does memory allocation once and filling up the string with the "+=" operation have a better performance than what it has been done in method_A?