I was just testing emplace_back or push_back(vector) or emplace or push (stack) and I got new info(just for me) that when a type of container is an object, emplace function is faster than push function. |
You're on the right track.
An
emplace function (-template) is occasionally
much faster, rarely slower, occasionally cleaner, and sometimes more error-prone than the corresponding
push function.
The performance difference is most significant for types that are
expensive to move as compared to
push_back. For example, given a type
T that is expensive to move,
ts.push_back(T(arg1, arg2, arg3)) would be significantly worse than
ts.emplace_back(arg1, arg2, arg3).
In the case you presented,
emplace_back avoids a move from the materialized temporary
std::string bound to the reference parameter of
push_back. Moving
std::string is a very cheap (almost free) operation. For very short strings like the ones you're working with, constructing the
std::string is just as cheap thanks to
small-buffer optimization inside
std::string. This is why the
emplace_back version is essentially twice as fast.