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

编程杂谈——使用emplace_back取代push_back

程序员文章站 2022-05-22 16:38:27
近日在YouTube视频上看到关于vector中emplace_back与push_back区别的介绍,深感自己在现代C++中还是有不少遗漏的知识点,遂写了段代码,尝试比较两者的差别。 示例代码 运行结果 结论 emplace_back方法可以不调用拷贝构造函数,所以理论上它应该比push_back ......

近日在youtube视频上看到关于vector中emplace_back与push_back区别的介绍,深感自己在现代c++中还是有不少遗漏的知识点,遂写了段代码,尝试比较两者的差别。

示例代码

#include <iostream>
#include <vector>
#include <functional>
#include <chrono>

class item
{
public:
    item(std::string name, bool display = true):name(name), display(display)
    {
        if (display)
            std::cout << "constructor: " << name << std::endl;
    }

    item(const item& item):name(item.name), display(item.display)
    {
        if (item.display)
            std::cout << "copy consturctor: " << item.name << std::endl;
    }
private:
    std::string name;
    bool display;
};

void calculate(std::vector<item>& v, int count, std::function<void()> const& f)
{
    clock_t begin_time = clock();
    for (auto i = 0; i < count; i++)
    {
        f();
    }

    std::cout << float(clock() - begin_time) / clocks_per_sec << std::endl;
}

int main()
{
    std::vector<item> v;
    v.reserve(2);

    v.push_back(item("push_back"));
    v.emplace_back("emplace_back", true);

    v.clear();

    int count = 100000;
    v.reserve(count);

    calculate(v, count, [&]() { v.push_back(item("push_back", false)); });

    v.clear();

    calculate(v, count, [&]() { v.emplace_back("emplace_back", false); });
}

运行结果

constructor: push_back
copy consturctor: push_back
constructor: emplace_back
0.431
0.28

结论

  • emplace_back方法可以不调用拷贝构造函数,所以理论上它应该比push_back性能更好
  • 经过10w次量级的数据计算,最终结果与预期一致
  • reserve方法必须要使用,可以减少分配内存时间,提升性能