Back to TILs

C++ emplace_back

Date: 2023-01-24Last modified: 2023-02-28

Table of contents

You should use push_back when:

You should use emplace_back when:

In general, use emplace back when building an element in place. When we need to build an object straight inside the container, we should use emplace back() since it will directly generate an object within the container, eliminating the need for a move/copy ().

struct Test {
  int a, b;
  Test(int x, int y) : a(x), b(y) {}
};
  std::vector<Test> v1;
  std::vector<Test> v2;
  auto start = std::chrono::high_resolution_clock::now();
  for (int i = 0; i < 1000000; ++i) {
    v1.push_back(Test(i, i));
  }
  auto end = std::chrono::high_resolution_clock::now();
  std::cout << "push_back took "
            << std::chrono::duration_cast<std::chrono::microseconds>(end -
                                                                     start)
                   .count()
            << " microseconds\n";

  start = std::chrono::high_resolution_clock::now();
  for (int i = 0; i < 1000000; ++i) {
    v2.emplace_back(i, i);
  }
  end = std::chrono::high_resolution_clock::now();
  std::cout << "emplace_back took "
            << std::chrono::duration_cast<std::chrono::microseconds>(end -
                                                                     start)
                   .count()
            << " microseconds\n";

  return 0;

Possible output

push_back took 67699 microseconds
emplace_back took 30729 microseconds

References