emplace_back和push_back性能对比

push_back()函数向容器中加入一个临时对象(右值元素)时, 首先会调用构造函数生成这个对象,然后条用拷贝构造函数将这个对象放入容器中, 最后释放临时对象。
emplace_back()函数向容器中中加入临时对象, 临时对象原地构造,没有赋值或移动的操作

#include 
#include 
#include 
#include 

struct data{
    int a;
    int b;
    int c;
    data(int a_ , int b_ , int c_): a(a_) , b(b_) , c(c_)    {

    }

    friend std::ostream & operator << (std::ostream &os, data &vt)//在类中或结构体中定义必须为友元类型,其他地方则不需要
    {
        os< vec1 , vec2;
    auto start_time = std::chrono::steady_clock::now();
    for (int i = 0 ; i < 10000000 ; ++i)
    {
        vec1.push_back(data(i , i , i));
    }
    auto end_time = std::chrono::steady_clock::now();
    auto cost_time = std::chrono::duration_cast(end_time - start_time).count();
    std::cout << "push_back cost time: " << cost_time << std::endl;

    start_time = std::chrono::steady_clock::now();
    for (int i = 0 ; i < 10000000 ; ++i)
    {
        vec2.emplace_back(i , i , i);
    }
    end_time = std::chrono::steady_clock::now();
    cost_time = std::chrono::duration_cast(end_time - start_time).count();
    std::cout << "emplace_back cost time: " << cost_time << std::endl;

    std::cout << "vec1[100]: " << vec1[100] << std::endl;
    std::cout << "vec2[100]: " << vec2[100] << std::endl;
    return 1;
}

运行结果

push_back cost time: 204
push_back cost time: 133
vec1[100]: 100,100,100
vec2[100]: 100,100,100

如果只是单纯的往容器中加入单个元素,二者性能并无多大差异。

你可能感兴趣的:(C++)