首页 > 解决方案 > 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. 算法 1 中的 CPU 缓存命中,而算法 2 调用 boost 库,因此 CPU 缓存未命中并导致速度降低
  2. 标准操作由编译器优化,而升压操作则不是。
  3. boost 使用的 std::search 不能很好地替代 std::find。

这些解释中哪个更合理?这是一个意想不到的行为,让我怀疑在我的代码库中使用 boost::string_ref。我的系统有 gcc 5.4.0 (C++14),boost 1.66,没有编译器优化标志(以 -O 开头)。

谢谢,

标签: c++stringoptimizationboostprofiling

解决方案


推荐阅读