欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

emplace_back和push_back性能对比

程序员文章站 2022-03-01 23:20:09
...

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

#include <opencv2/opencv.hpp>
#include <iostream>
#include <chrono>
#include <vector>

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<<vt.a<<","<<vt.b << "," << vt.c << std::endl ;
        return os ;
    }
};

int main()
{
    std::vector<data> 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<std::chrono::milliseconds>(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<std::chrono::milliseconds>(end_time - start_time).count();
    std::cout << "push_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++