Consider the following program. Why is move slower than copy? I thought that move semantics sped things up considerably when returning locals as rvalues from functions. Can you tell me why moving a large vector is slower than copying it. The benchmark for returning a shared_ptr is provided as a base case.
#include <iostream>
#include <vector>
#include <string>
#include <chrono>
using namespace std;
vector<int> getStringByCopy()
{
vector<int> v;
for (int x = 0; x< 15000000;x++) v.push_back(x);
return v;
}
vector<int>&& getStringByMove()
{
vector<int> v;
for (int x = 0; x< 15000000;x++) v.push_back(x);
return move(v);
}
shared_ptr<vector<int>> getStringByPointer()
{
shared_ptr<vector<int>> v = make_shared<vector<int>>();
for (int x = 0; x< 15000000;x++) v->push_back(x);
return v;
}
int main(int argc, const char * argv[]) {
// insert code here...
chrono::system_clock::time_point begin = chrono::system_clock::now();
vector<int> v = getStringByCopy();
chrono::system_clock::time_point end = chrono::system_clock::now();
cout << v[0] << "copy took " << chrono::duration_cast<chrono::microseconds>(end - begin).count() << endl;;
begin = chrono::system_clock::now();
vector<int>&& m = getStringByMove();
end = chrono::system_clock::now();
cout << m[0] << "move took " << chrono::duration_cast<chrono::microseconds>(end - begin).count() << endl;;
begin = chrono::system_clock::now();
shared_ptr<vector<int>> sp = getStringByPointer();
end = chrono::system_clock::now();
cout << (*sp)[0] << "pointer took " << chrono::duration_cast<chrono::microseconds>(end - begin).count() << endl;
return 0;
}
The output is:
0copy took 437043
0move took 462803
0pointer took 394549