Reputation:
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?
Upvotes: 0
Views: 665
Reputation: 85351
This would be platform, compiler and compile flags-dependent.
emplace_back
version would need to increment vector size
each time.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:
Clang 11 -O3: emplace_back
is much faster:
MSVC 19.6 /O2: emplace_back
slightly faster:
-----------------------------------------------------
Benchmark Time CPU Iterations
-----------------------------------------------------
Emplace 138 ns 136 ns 4480000
Index 159 ns 160 ns 4977778
Upvotes: 5