【发布时间】:2018-01-18 02:19:14
【问题描述】:
在观看了 Titus Winters 的 "Live at Head" 演讲后,他提到 StrCat() 是人们最喜欢的功能之一,我决定尝试实现类似的东西,看看我是否可以击败 std::string::append(或就运行时性能而言,operator+,我认为它在内部使用 append 。我的理由是,作为可变参数模板实现的 strcat() 函数将能够确定其所有类似字符串的参数的组合大小,并进行一次分配来存储最终结果,而不必在以下情况下不断重新分配operator+,它不知道调用它的总体上下文。
但是,当我将我的自定义实现与 quick-bench 上的 operator+ 进行比较时,我发现我的 strcat() 实现在使用 -std=c++17 -O3 编译的最新版本的 clang 和 gcc 上比 operator+ 慢约 4 倍。我在下面包含了快速工作台代码以供参考。
有人知道是什么原因导致这里速度变慢吗?
#include <cstring>
#include <iostream>
#include <string>
// Get the size of string-like args
int getsize(const std::string& s) { return s.size(); }
int getsize(const char* s) { return strlen(s); }
template <typename S>
int strcat_size(const S& s) {
return getsize(s);
}
template <typename S, typename... Strings>
int strcat_size(const S& first, Strings... rest) {
if (sizeof...(Strings) == 0) {
return 0;
} else {
return getsize(first) + strcat_size(rest...);
}
}
// Populate a pre-allocated string with content from another string-like object
template <typename S>
void strcat_fill(std::string& res, const S& first) {
res += first;
}
template <typename S, typename... Strings>
void strcat_fill(std::string& res, const S& first, Strings... rest) {
res += first;
strcat_fill(res, rest...);
}
template <typename S, typename... Strings>
std::string strcat(const S& first, Strings... rest) {
int totalsize = strcat_size(first, rest...);
std::string res;
res.reserve(totalsize);
strcat_fill(res, first, rest...);
return res;
}
const char* s1 = "Hello World! ";
std::string s2 = "Here is a string to concatenate. ";
std::string s3 = "Here is a longer string to concatenate that avoids small string optimization";
const char* s4 = "How about some more strings? ";
std::string s5 = "And more strings? ";
std::string s6 = "And even more strings to use!";
static void strcat_bench(benchmark::State& state) {
// Code inside this loop is measured repeatedly
for (auto _ : state) {
std::string s = strcat(s1, s2, s3, s4, s5, s6);
benchmark::DoNotOptimize(s);
}
}
BENCHMARK(strcat_bench);
static void append_bench(benchmark::State& state) {
for (auto _ : state) {
std::string s = s1 + s2 + s3 + s4 + s5 + s6;
benchmark::DoNotOptimize(s);
}
}
BENCHMARK(append_bench);
【问题讨论】:
-
我可能是错的,但我相信可变参数模板(正如你所写的那样)会产生副本。您需要通过
Strings&&... rest接受并使用std::forward,例如this answer -
@vu1p3n0x 你是对的。完美的转发使它更快。在这种情况下,虽然它似乎与传递
const引用一样好。
标签: c++ performance benchmarking string-concatenation abseil