string move正確用法與效能測試
阿新 • • 發佈:2019-01-22
直接上程式碼和執行結果
#include <iostream>
#include <string>
#include <sys/time.h>
using namespace std;
const int run_time = 1000*1000;
void CreateStr(string& str)
{
for(int i = 0; i < 100000; ++i)
str += rand()%26 + 'a';
}
std::string GetStr(string& str)
{
return std::move(str);
}
std ::string GetStr2(string& str)
{
return str;
}
int main()
{
string str;
string mov_str;
CreateStr(str);
timeval st, et;
gettimeofday(&st, NULL);
for(int i = 0; i < run_time; ++i)
{
mov_str = std::move(GetStr(str));
str = std::move(mov_str);
}
gettimeofday(&et, NULL);
cout << "use std::move, time:" << (et.tv_sec-st.tv_sec)*1000 + (et.tv_usec-st.tv_usec)/1000 << "ms" << endl;
gettimeofday(&st, NULL);
for(int i = 0; i < run_time; ++i)
{
mov_str = GetStr2(str);
str = std::move(mov_str);
}
gettimeofday(&et, NULL);
cout << "return directly in function, time:" << (et.tv_sec-st.tv_sec)*1000 + (et.tv_usec-st.tv_usec)/1000 << "ms" << endl;
gettimeofday(&st, NULL);
for(int i = 0; i < run_time; ++i)
{
mov_str = GetStr(str);
str = (mov_str);
}
gettimeofday(&et, NULL);
cout << "use assgin after function, time:" << (et.tv_sec-st.tv_sec)*1000 + (et.tv_usec-st.tv_usec)/1000 << "ms" << endl;
return 0;
}
執行結果:
正確用法:
在函式內使用std::move返回,函式返回時仍用std::move賦值。