48

I thought that emplace_back would be the winner, when doing something like this:

v.push_back(myClass(arg1, arg2));

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. For more see this question.

Google also gives this and this questions.

I decided to compare them for a vector that would be filled by integers.

Here is the experiment code:

#include <iostream>
#include <vector>
#include <ctime>
#include <ratio>
#include <chrono>

using namespace std;
using namespace std::chrono;

int main() {

  vector<int> v1;

  const size_t N = 100000000;

  high_resolution_clock::time_point t1 = high_resolution_clock::now();
  for(size_t i = 0; i < N; ++i)
    v1.push_back(i);
  high_resolution_clock::time_point t2 = high_resolution_clock::now();

  duration<double> time_span = duration_cast<duration<double>>(t2 - t1);

  std::cout << "push_back took me " << time_span.count() << " seconds.";
  std::cout << std::endl;

  vector<int> v2;

  t1 = high_resolution_clock::now();
  for(size_t i = 0; i < N; ++i)
    v2.emplace_back(i);
  t2 = high_resolution_clock::now();
  time_span = duration_cast<duration<double>>(t2 - t1);
  std::cout << "emplace_back took me " << time_span.count() << " seconds.";
  std::cout << std::endl;

  return 0;
}

The result is that emplace_back is faster.

push_back took me 2.76127 seconds.
emplace_back took me 1.99151 seconds.

Why? The answer of the 1st linked question clearly says that there will be no performance difference.

Also tried with other time methods, but got identical results.

[EDIT] Comments say that testing with ints doesn't say anything and that push_back takes a ref.

I did the same test in the code above, but instead of int I had a class A:

class A {
 public:
  A(int a) : a(a) {}
 private:
  int a;
};

Result:

push_back took me 6.92313 seconds.
emplace_back took me 6.1815 seconds.

[EDIT.2]

As denlan said, I should also change the position of the operations, so I swapped them and in both situation (int and class A), emplace_back was again the winner.

[SOLUTION]

I was running the code in debug mode, which makes the measurements invalid. For benchmarking, always run the code in release mode.

4
  • So, does it mean that you do not see these performance differences when you use in release mode? Do you have numbers for the same? Oct 21, 2019 at 15:26
  • Hey @talekeDskobeDa, I was executing this code in my old dead laptop, so no, sorry.
    – gsamaras
    Oct 21, 2019 at 15:32
  • I understand that in principal emplace_back would be faster – certainly not slower. What I don't understand (and can't find anywhere) is why even in this simplest case you have, why the optimizer doesn't produce the same code. Any ideas?
    – Ben
    Nov 22, 2019 at 17:21
  • Not really @Ben, but if you'd like, you could post a new question, linking to my question, asking exactly that (if you do share it with me please). :)
    – gsamaras
    Nov 22, 2019 at 19:41

2 Answers 2

58

Your test case isn't very helpful. push_back takes a container element and copies/moves it into the container. emplace_back takes arbitrary arguments and constructs from those a new container element. But if you pass a single argument that's already of element type to emplace_back, you'll just use the copy/move constructor anyway.

Here's a better comparison:

Foo x; Bar y; Zip z;

v.push_back(T(x, y, z));  // make temporary, push it back
v.emplace_back(x, y, z);  // no temporary, directly construct T(x, y, z) in place

The key difference, however, is that emplace_back performs explicit conversions:

std::vector<std::unique_ptr<Foo>> v;
v.emplace_back(new Foo(1, 'x', true));  // constructor is explicit!

This example will be mildly contrived in the future, when you should say v.push_back(std::make_unique<Foo>(1, 'x', true)). However, other constructions are very nice with emplace, too:

std::vector<std::thread> threads;
threads.emplace_back(do_work, 10, "foo");    // call do_work(10, "foo")
threads.emplace_back(&Foo::g, x, 20, false);  // call x.g(20, false)
2
  • I think your v.emplace_back(new Foo(1, 'x', true)); isn't exception safe, since it creates the new Foo then calls emplace_back which could throw, leaving the Foo leaked.
    – Ben
    Nov 22, 2019 at 17:19
  • 1
    @Ben: That's true. Hence std::make_unique, to allow a safe and not too verbose solution.
    – Kerrek SB
    Nov 24, 2019 at 0:43
2

First, my answer to that question: emplace member functions don't always perform faster than push member functions, sometimes they are the same in terms of efficiency.

According to my understanding from "C++ Primer" about the difference between emplace and push member functions, the former ones including emplace_back are called for passing arguments to a constructor for the element type. That means, the emplace members use those arguments to construct an element directly in space managed by the container. But in this case, note that the direct initialization of container element mentioned only takes place when the given arguments need to be implicitly converted to the element type, or say, the given arguments are not of element type but "compatible" with it. Otherwise the copy/move constructor are called, which should "cost" the same as push members are called. In contrast, when the push members are called, we have to pass objects of the element type and those objects are then copied into the container. As a result in this case, the extra copy step in copy initialization specific to push members should cost more time. Similar to the example for comparison provided by yizzlez, here is my simple example illustrating the two cases in differentiating emplace_back and push_back I mentioned:

class T 
{
public:
  T()=default;
  explicit T(const std::string& rstr) : str(rstr) { }
  T(const T&);  //the same as synthesized copy constructor
private:
  std::string str;
}

const std::string test = "testing";
std::vector<T> vec_t;
// better executing efficiency achieved by emplace_back
vec_t.emplace_back(test);  // explicit constructor is called behind
vec_t.push_back(T(test));
// the same executing efficiency
vec_t.emplace_back(T(test));  // copy constructor is called behind
vec_t.push_back(T(test));

Consequently, similar to the first example provided by yizzlez, the corresponding emplace_back method results in less verbose and potentially more efficient code where an explicitly-constructed temporary of the container element type is necessary in calling push_back method, as you can refer in this more concrete link.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.