c++ - boost::string_ref 比 std::string 复制慢
问题描述
我已经实现了一个算法 1) 使用普通字符串副本和 2) 使用 boost::string_view 在分隔符之后查找字符串的后缀部分。我已经分析了代码并且违反直觉,我最终看到 boost::string_view 表现不佳。
std::string algorithm1(const std::string &mine, const std::string& path) {
size_t startPos = mine.find(path);
std::string temp;
if (startPos != mine.npos) {
startPos += path.size();
temp = mine.substr(startPos);
} else {
std::cout << "not found" << std::endl;
return "";
}
return temp;
}
boost::string_ref algorithm2(boost::string_ref mine, boost::string_ref path) {
size_t startPos = mine.find(path);
boost::string_ref temp;
if (startPos != mine.npos) {
startPos += path.size();
temp = mine.substr(startPos);
} else {
std::cout << "not found" << std::endl;
}
return temp;
}
int main(int argc, char* argv[])
{
std::cout << "entered" << std::endl;
const std::string mine = "sth/aStr/theSuffixWeDesire";
const std::string path = "/aStr/";
for (size_t i = 0; i < 10; i++)
{
assert (algorithm1(mine, path) == "theSuffixWeDesire");
assert (algorithm2(mine, path) == "theSuffixWeDesire");
}
return 0;
}
当我用 uftrace 分析代码时,每次迭代我最终得到: algorithm1 耗时 2,083 ns,内部调用 std::find algorithm2 耗时 11,835 ns,调用 std::search 花费的时间最长可能有三个原因我能想到:
- 算法 1 中的 CPU 缓存命中,而算法 2 调用 boost 库,因此 CPU 缓存未命中并导致速度降低
- 标准操作由编译器优化,而升压操作则不是。
- boost 使用的 std::search 不能很好地替代 std::find。
这些解释中哪个更合理?这是一个意想不到的行为,让我怀疑在我的代码库中使用 boost::string_ref。我的系统有 gcc 5.4.0 (C++14),boost 1.66,没有编译器优化标志(以 -O 开头)。
谢谢,
解决方案
推荐阅读
- c# - C#输出数组的最小数
- r - R - 基于列名(在向量中)和这些列中的特定值的子集行
- python - 如何使用 Beautifulsoup 从嵌套的 html 表中获取文本?
- javascript - 对 PIE 的 HighCharts 注释
- autohotkey - 如何下载保管箱文件?
- aws-lambda - 通过 API 网关测试 Java lambda 函数:无法确定要授权的服务/操作名称
- cypress - 赛普拉斯缓存 - 服务器会话已过期
- r - 提取模式会影响我在数据框中的数值变量
- web-scraping - 如何自动化网站中按钮的 API 调用?
- java - Kafka 消费者无法连接时快速失败