std::move性能测试和应用范例

string move正确用法与性能测试

直接上代码和运行结果

代码

#include <iostream>
#include <string>
#include <sys/time.h>
using namespace std;

const int kRunTime = 1000*1000;     // 循环次数
const int kStringLength = 100000;   // 字符串长度
void CreateStr(string& str)
{
    for(int i = 0; i < kStringLength; ++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);     // 产生一个随机的字符串
    std::cout << "test string len = " << str.length() << ", loop times = " << kRunTime << std::endl;

    timeval st, et;
    gettimeofday(&st, NULL);
    for(int i = 0; i < kRunTime; ++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;
    // 从这里打印mov_str.size = 0我们也可以看到被move的对象不能再被使用,因为其内存空间已经被转移到其他对象。
    cout << "mov_str.size = " << mov_str.size() << endl << endl;
    gettimeofday(&st, NULL);
    for(int i = 0; i < kRunTime; ++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;
    cout << "mov_str.size = " << mov_str.size() << endl << endl;
    gettimeofday(&st, NULL);
    for(int i = 0; i < kRunTime; ++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;
    cout << "mov_str.size = " << mov_str.size() << endl;
    return 0;
}

运行结果

test string len = 100000, loop times = 1000000
use std::move, time:57ms
return directly in function, time:6513ms
use assgin after function, time:7561ms

正确用法

在函数内使用std::move返回,函数返回时仍用std::move赋值。
但是某对象在被使用std::move后,不能再正常地使用它。

参考

[1] string move正确用法与性能测试

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

流媒体程序员

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值