Life is short, use emplace_back()。探究一下C++11的push_back, move, rvalue, emplace_back

版权声明:本文为博主原创文章,未经博主允许不得转载。博客主页:http://blog.csdn.net/u013390476 https://blog.csdn.net/u013390476/article/details/52040225

前言

一直以来写代码,vector想都没想就是push_back,今天发现的C++11的emplace_back碾压了传统的push_back

总结一句话:Life is short, use emplace_back()

简单叙述原因:emplace_back可以“同时构造和插入,一次搞定”,push_back需要“先构造,后插入,而且插入的时候还伴随着拷贝或者移动”。


Talk is cheap, show me the code

#include <iostream>
#include <utility>
#include <chrono>
#include <vector>
#include <string>
using namespace std;
using namespace chrono;


int main()
{
    vector<string> v;
    int num = 100000;
    v.reserve(num);                    // capacity 一次性增大到十万,减少vector多次增大时候的拷贝次数

    cout << "push_back way one:     ";
    auto start = system_clock::now();
    for (int i = 0; i < num; ++i)
    {
        string temp("caitao");
        v.push_back(temp);             // push_back(const string&),参数是左值引用
    }
    auto end = system_clock::now();
    auto duration = duration_cast<microseconds>(end - start);
    cout << duration.count() << " microseconds." << endl << endl;

    cout << "push_back way two:     ";
    v.clear();
    start = system_clock::now();
    for (int i = 0; i < num; ++i)
    {
        string temp("caitao");
        v.push_back(move(temp));       // push_back(string &&), 参数是右值引用。
        // move可以理解为类型转换:左值引用 → 右值引用。右值引用就是临时对象。
    }
    end = system_clock::now();
    duration = duration_cast<microseconds>(end - start);
    cout << duration.count() << " microseconds." << endl << endl;

    cout << "push_back way three:   ";
    v.clear();
    start = system_clock::now();
    for (int i = 0; i < num; ++i)
    {
        v.push_back(string("caitao")); // push_back(string &&), 参数是右值引用
    }
    end = system_clock::now();
    duration = duration_cast<microseconds>(end - start);
    cout << duration.count() << " microseconds." << endl << endl;

    cout << "push_back way four:    ";
    v.clear();
    start = system_clock::now();
    for (int i = 0; i < num; ++i)
    {
        v.push_back("caitao");         // push_back(string &&),参数是右值引用,和 way three 几乎一样(只有vector元素是string才可以这么写,为了C++和C的字符串兼容)
    }
    end = system_clock::now();
    duration = duration_cast<microseconds>(end - start);
    cout << duration.count() << " microseconds." << endl << endl;

    cout << "emplace_back(fastest): ";
    v.clear();
    start = system_clock::now();
    for (int i = 0; i < num; ++i)
    {
        v.emplace_back("caitao");      // 只有一次构造函数,不调用拷贝构造函数,速度最快
    }
    end = system_clock::now();
    duration = duration_cast<microseconds>(end - start);
    cout << duration.count() << " microseconds." << endl << endl;

    system("pause");
    return 0;
}

分析

push_back emplace_back

第一种方法,速度最慢。push_back的参数是左值引用。首先定义一个temp对象的时候,调用一次构造函数,然后push_back的时候调用一次拷贝构造函数。两次构造很花时间,因为内存里面需要重新分配空间。

第二~四种方法,速度中等。push_back的参数是右值引用。首先定义一个temp对象的时候,调用一次构造函数,然后push_back的时候调用一次移动构造函数。移动构造函数花的时间比拷贝构造函数花的时间,因为不需要内存重新分配空间。(不知道为什么第二种方法会比方法三和四花费的时间多一点点。。。)

第五种方法,即emplace_back速度最快,因为emplace_back只调用一次构造函数,没有移动构造函数,也没有拷贝构造函数。cplusplus.com说:Arguments forwarded to construct the new element. 意思是:emplace_back的参数就是构造函数的参数。


证明上述的分析

写一个类,重载构造函数,重载拷贝构造函数,重载移动构造函数。代码如下:

#include <vector> 
#include <string>
#include <iostream>
using namespace std;

struct Complicated
{
    int year;
    double country;
    string name;

    Complicated(int a, double b, string c) :year(a), country(b), name(c)
    {
        cout << "is constucted" << endl;
    }

    Complicated(const Complicated & other) : year(other.year), country(other.country), name(other.name)
    {
        cout << "is copied" << endl;
    }

    Complicated(Complicated && other) : year(move(other.year)), country(move(other.country)), name(move(other.name))
    {
        cout << "is moved" << endl;
    }
};

int main()
{
    int anInt = 4;
    double aDouble = 5.0;
    string aString = "C++";

    vector<Complicated> v;
    v.reserve(10);

    cout << "--emplace_back--" << endl;
    v.emplace_back(anInt, aDouble, aString);            // construct

    cout << endl << "--push_back--" << endl;
    Complicated temp(anInt, aDouble, aString);          // construct
    cout << endl;

    v.push_back(temp);                                  // copy
    cout << endl;

    v.push_back(move(temp));                            // move
    cout << endl;

    v.push_back(Complicated(anInt, aDouble, aString));  // construct + move
    cout << endl;

    system("pause");
    return 0;
}

输出结果如下:
move_copy



一种“更加公平”的比较方式

emplace_back可以“构造和插入同时进行”,堪称“开挂”。如果对象构造好了,只是单纯的比较插入(抛开外挂),谁快一些呢?

这次是“单纯”比较的push_back和emplace_back的插入功能:

#include <iostream>
#include <utility>
#include <chrono>
#include <vector>
#include <string>
using namespace std;
using namespace chrono;

int main()
{
    vector<string> v;
    int num = 100000;
    v.reserve(num);                    // capacity 一次性增大到十万,减少vector多次增大时候的拷贝次数

    string caitao("caitao");
    vector<string> storage(num, caitao);

    cout << "push_back(copy):  ";
    auto start = system_clock::now();
    for (int i = 0; i < num; ++i)
    {
        v.push_back(storage[i]);
    }
    auto end = system_clock::now();
    auto duration = duration_cast<microseconds>(end - start);
    cout << duration.count() << " microseconds." << endl << endl;

    cout << "push_back:(move): ";
    v.clear();
    start = system_clock::now();
    for (int i = 0; i < num; ++i)
    {
        v.push_back(move(storage[i]));
    }
    end = system_clock::now();
    duration = duration_cast<microseconds>(end - start);
    cout << duration.count() << " microseconds." << endl << endl;

    cout << "emplace_back:     ";
    v.clear();
    start = system_clock::now();
    for (int i = 0; i < num; ++i)
    {
        v.emplace_back(storage[i]);
    }
    end = system_clock::now();
    duration = duration_cast<microseconds>(end - start);
    cout << duration.count() << " microseconds." << endl << endl;

    system("pause");
    return 0;
}

emplace_back

emplace_back最快,push_back(move())次之,push_back最慢。所以呀,大家忘了push_back吧(除非特殊情况,比如?)


last update: 2017/5/10

猜你喜欢

转载自blog.csdn.net/u013390476/article/details/52040225
今日推荐