【发布时间】:2023-03-13 07:22:01
【问题描述】:
测试此代码后:
#include <iostream>
#include <chrono>
#include <vector>
#include <string>
void x(std::vector<std::string>&& v){ }
void y(const std::vector<std::string>& v) { }
int main() {
std::vector<std::string> v = {};
auto tp = std::chrono::high_resolution_clock::now();
for (int i = 0; i < 1000000000; ++i)
x(std::move(v));
auto t2 = std::chrono::high_resolution_clock::now();
auto time = std::chrono::duration_cast<std::chrono::duration<double>>(t2 - tp);
std::cout << "1- It took: " << time.count() << " seconds\n";
tp = std::chrono::high_resolution_clock::now();
for (int i = 0; i < 1000000000; ++i)
y(v);
t2 = std::chrono::high_resolution_clock::now();
time = std::chrono::duration_cast<std::chrono::duration<double>>(t2 - tp);
std::cout << "2- It took: " << time.count() << " seconds\n";
std::cin.get();
}
我知道使用 const-reference 实际上比使用移动语义快约 15 秒,这是为什么呢?我认为移动语义更快,否则,他们为什么要添加它们?我对移动语义有什么误解?谢谢
【问题讨论】:
-
你的函数是空的,除了参数传递设置之外你没有测试任何东西——也就是说,如果调用没有完全优化。也许一个得到优化而另一个没有?您应该查看或发布生成的代码。
-
您的
x采用&&这一事实表明您不了解移动语义。考虑阅读this question and answers。 -
移动是对 copy 的优化(对于 xvalues),而不是通过引用传递。当然传递一个简单的引用会更快。
-
你开启优化了吗?
标签: c++ c++11 constants move const-reference