string move正确用法与性能测试

直接上代码和运行结果

#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赋值。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值