According to this article, using std::move avoids copy,thus improve function performance. I have tested in linux with vscode + gcc9.4, the results not comply with what the article said.
#include <iostream>
#include <chrono>
template <typename T>
void swap1(T& a, T& b)
{
T tmp(a); // now we have two copies of a
a = b; // now we have two copies of b
b = tmp; // now we have two copies of tmp (aka a)
}
template <typename T>
void swap2(T& a, T& b)
{
T tmp(std::move(a));
a = std::move(b);
b = std::move(tmp);
}
int main()
{
int a = 10;
int b = 20;
int num = 100000;
const auto& time_t1 = std::chrono::steady_clock::now();
for(int i = 0; i < num; i++){
swap1(a,b);
}
const auto& time_t2 = std::chrono::steady_clock::now();
double time_lf = (time_t2 - time_t1).count() / 1000000.0;
std::cout<<"time_lf: "<<time_lf<<std::endl;
const auto& time_t3 = std::chrono::steady_clock::now();
for(int i = 0; i < num; i++){
swap2(a,b);
}
const auto& time_t4 = std::chrono::steady_clock::now();
double time_move = (time_t4 - time_t3).count() / 1000000.0;
std::cout<<"time_move: "<<time_move<<std::endl;
return 0;
}
outputs are:
time_lf: 0.177079
time_move: 0.384381
why using std::move doesn't improve performance of function swap();