In a member function, I want to return a newly created vector of strings.
Which version is the most efficient from a memory allocation & constructor calling point of view? theString(i)
returns a const std::string &
std::vector<std::string> result(depth());
for(int i=0;i<depth;i++) {
result[i] = theString(i);
}
or
std::vector<std::string> result;
result.reserve(depth());
for(int i=0;i<depth;i++) {
result.emplace_back(theString(i));
}
To me it seems that:
- Solution 1 constructs every empty string first, then copy-assigns them => not perfect
- Solution 2 is better since it will copy-construct every string, while the vector data is allocated once by
reserve
(or is there an even more efficient solution?)