![](/img/trans.png)
[英]Why are standard string functions faster than my custom string functions?
[英]Why C++ standard string copy is faster than string move?
认为字符串复制操作应该比移动慢,但基准测试表明它更快。
static void StringCreationMove(benchmark::State & state) {
std::string x = "hello";
for (auto _ : state) {
std::string created_string_move(std::move(x));
benchmark::DoNotOptimize(created_string_move);
}
}
BENCHMARK(StringCreationMove);
static void StringCreationCopy(benchmark::State & state) {
std::string x = "hello";
for (auto _ : state) {
std::string created_string_copy(x);
benchmark::DoNotOptimize(created_string_copy);
}
}
BENCHMARK(StringCreationCopy);
如果move
没有分配 memory,为什么它很慢? 或者,这个基准本身可能有问题。
更新
更新的版本可能会反映更多的见解。
#include <benchmark/benchmark.h>
static void StringCreationMove(benchmark::State & state) {
for (auto _ : state) {
std::string x = "hello";
benchmark::DoNotOptimize(x);
std::string created_string_move(std::move(x));
benchmark::DoNotOptimize(created_string_move);
}
}
BENCHMARK(StringCreationMove);
static void StringCreationCopy(benchmark::State & state) {
for (auto _ : state) {
std::string x = "hello";
benchmark::DoNotOptimize(x);
std::string created_string_copy(x);
benchmark::DoNotOptimize(created_string_copy);
}
}
BENCHMARK(StringCreationCopy);
BENCHMARK_MAIN();
结果在我的 MacBook Air 2013 上。
Run on (4 X 1300 MHz CPU s)
CPU Caches:
L1 Data 32 KiB (x2)
L1 Instruction 32 KiB (x2)
L2 Unified 256 KiB (x2)
L3 Unified 3072 KiB (x1)
Load Average: 1.51, 1.49, 1.74
-------------------------------------------------------------
Benchmark Time CPU Iterations
-------------------------------------------------------------
StringCreationMove 72.0 ns 67.6 ns 11394713
StringCreationCopy 47.1 ns 47.1 ns 14960781
如果您使用标准的 libstd++ (GNU) 或 libc++ (llvm),基准测试结果会有所不同。 最后给出的移动速度更快: https://quick-bench.com/q/DV-lRSuipynW2QilZZvCV91uWHY
至于你的问题的答案。 字符串“hello”太短,应用了小字符串优化。 这意味着一个小数组用于小字符串,因此没有移动的优势。 这取决于实现,但可能 GNU std::string 在执行移动时不会以最佳方式复制数组的数据。 如果你使用足够长的弦,移动总是更快。
GNU: https://quick-bench.com/q/QFlfvUJ_Rua6g95koevFZsNaLrg LLVM: https://quick-bench.com/q/iJgfzrWc3yNUMkBYnbPI02e1lW4
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.