Is emplace_back faster than setting an index?

Which would be faster?

std::vector< std::string > vec;
vec.reserve(10);
for (int i=0; i < 10; i++){
    vec.emplace_back("Some text");
}

or

std::vector< std::string > vec;
vec.resize(10);
for (int i=0; i < 10; i++){
    vec[i] = "Some Text";
}

and if one of them is faster than the other (with size of 10) which one is more scalable?

Answer

This would be platform, compiler and compile flags-dependent.

  • The emplace_back version would need to increment vector size each time.
  • The indexed version would have to create empty string objects to pre-fill the vector.

So there is no way to tell without analyzing the generated code and/or measuring it.

According to google benchmark, the emplace_back version is faster:

GCC 10.2 -O3: emplace_back slightly faster:

enter image description here

Clang 11 -O3: emplace_back is much faster:

enter image description here

MSVC 19.6 /O2: emplace_back slightly faster:

-----------------------------------------------------
Benchmark           Time             CPU   Iterations
-----------------------------------------------------
Emplace           138 ns          136 ns      4480000
Index             159 ns          160 ns      4977778