Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ vector emplace_back is faster?

Tags:

c++

vector

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])
like image 739
WhatABeautifulWorld Avatar asked Dec 14 '12 17:12

WhatABeautifulWorld


People also ask

Why is Emplace_back faster?

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.

Which is faster Push_back or Emplace_back?

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.

What is Emplace_back in 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.

When should I use Emplace_back?

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.


1 Answers

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.

like image 109
Mike Seymour Avatar answered Oct 03 '22 01:10

Mike Seymour