Is std::string::push_back faster than std::string::append?

394 Views Asked by At

I usually use the += operator to add content to an std::string which is seemingly the same as std::string::append. There is also the push_back method for a string which allows to add one character at a time. For now, I always use += since it is readable compared to other methods, even if I only want to add one character.

Should I prefer push_back when I need to append one character only? Are there any performance issues significant enough to use push_back when adding one character?

1

There are 1 best solutions below

1
Enlico On BEST ANSWER

Since your question is limited by this

when I need to append one character only?

I think it's fair we keep basic_string& operator+=(const _CharT*) out of the question and concentrate on basic_string& operator+=(_CharT) vs void push_back(_CharT).

In this case, as far as GCC is concerned, += simply calls push_back and returns *this by reference,

_GLIBCXX20_CONSTEXPR
basic_string&
operator+=(_CharT __c)
{
    this->push_back(__c);
    return *this;
}

so the performance should be the same.

Most likely, other implementation of the STL will use a similar approach.