创建并返回字符串向量——最有效的解决方案
Create and return a vector of strings - most efficient solution?
在成员函数中,我想返回一个新创建的字符串向量。哪个版本是最有效的内存分配&构造函数调用的观点?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
分配一次
(或者有没有更有效的解决方案?)
给出一个通用的答案是不可能的:根据您的编译器、您正在使用的标准库实现、目标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)); }
如果它比你的候选人差得多,我会很惊讶的。它依赖于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_t
和char const*
),但只有在引用的字符串被保证在string_view
的最后使用之后才可行。
相关文章:
- 运行同一解决方案的另一个项目的项目
- Project Euler问题4的错误解决方案
- 计算每个节点的树高,帮助我解释这个代码解决方案
- C++:Application.cpp中抛出了未解析的外部符号(解决方案在问题的末尾,供未来的读者参考)
- visual c++,如何获取解决方案目录中的代码
- 使用通常称为 API 实现C++多个客户和生产者解决方案,这是否有效?
- 哪些有效的解决方案可以检查Arraya是否包含Arrayb的所有元素
- 是否有一种记忆有效的方法来探索从输入排列产生的解决方案
- 当仅恒定项之一变化时,线性系统AX = B的有效解决方案
- 对于同一循环的这两个连续组,是否有更有效的解决方案
- 遍历数组的简单任务.以下哪种解决方案最有效
- 将一维矩阵数组转换为主一维矩阵的有趣算法挑战,需要有效的解决方案
- 找到解决方案的最有效方法-C++
- 神经网络图像分类,最有效的解决方案/建议
- 如何想出这样的解决方案?(检查数独是否有效)
- 创建并返回字符串向量——最有效的解决方案
- 欧拉#5项目;这个解决方案有效 - 但为什么
- 给定一个范围,我必须计算数组中数字的频率.给定的解决方案是否有效
- 有效测试多个学生的编程解决方案
- 使用可变模板(或其他解决方案)有效地对数据施加结构