0

在成员函数中,我想返回一个新创建的字符串向量。从内存分配和构造函数调用的角度来看,哪个版本最有效?theString(i)返回一个const std::string &

std::vector<std::string> result(depth());
for(int i=0;i<depth;i++) {
    result[i] = theString(i);
}

或者

std::vector<std::string> result;
result.reserve(depth());
for(int i=0;i<depth;i++) {
    result.emplace_back(theString(i));
}

在我看来:

  • 解决方案 1 首先构造每个空字符串,然后复制分配它们 => 不完美
  • 解决方案 2 更好,因为它将复制构造每个字符串,而向量数据由reserve

(或者有没有更有效的解决方案?)

4

1 回答 1

2

不可能给出一个通用的答案:取决于您的编译器、您使用的标准库实现、目标 CPU 和周围的源代码,发出的代码可能会有所不同。此外,一种方案或另一种方案是否更快也可能受到不同调度引起的缓存效应或线程切换效应的影响。

所以,不幸的是,没有通用的答案:用你的设置来衡量。

话虽如此,让我提供另外两个候选人;候选人3:

// The simplest code is always easier to read:
std::vector<std::string> result;
for (size_t i = 0; i < depth; ++i) { result.emplace_back(theString(i)); }

如果它比您的候选 2 差得多,我会感到惊讶。它依赖于vector' 摊销常数emplace_back和移动字符串便宜的事实(与复制相比)。

候选人4:

// If no copy is necessary, then no copy is cheaper:
std::vector<std::string_view> result; // or another "StringRef" alternative
for (size_t i = 0; i < depth; ++i) { result.emplace_back(theString(i)); }

后者依赖于string_view:对字符串的非拥有引用,这是实现起来非常简单的事情(基本上是一对size_tand char const*),但只有在保证引用的字符串比最后一次使用string_view.

于 2014-05-11T17:51:08.180 回答