If I have a class
class foo {
public:
foo() { // spend some time and do something. }
private:
// some data here
}
Now I have a vector of foo, I want to put this vector into another vector
vector<foo> input; // assume it has 5 elements
vector<foo> output;
Is there ANY performance difference with these two lines?
output.push_back(input[0])
output.emplace_back(input[0])
because emplace_back would construct the object immediately in the vector, while push_back , would first construct an anonymous object and then would copy it to the vector.
With the simple benchmark here, we notice that emplace_back is 7.62% faster than push_back when we insert 1,000,000 object (MyClass) into an vector.
vector::emplace_back()This function is used to insert a new element into the vector container, the new element is added to the end of the vector.
Specific use case for emplace_back : If you need to create a temporary object which will then be pushed into a container, use emplace_back instead of push_back . It will create the object in-place within the container. Notes: push_back in the above case will create a temporary object and move it into the container.
Is there ANY performance difference with these two lines?
No, both will initialise the new element using the copy constructor.
emplace_back
can potentially give a benefit when constructing with more (or less) than one argument:
output.push_back(foo{bar, wibble}); // Constructs and moves a temporary
output.emplace_back(bar, wibble); // Initialises directly
The true benefit of emplace
is not so much in performance, but in allowing non-copyable (and in some cases non-movable) elements to be created in the container.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With