當前位置:
首頁 > 知識 > std::vector::push_back和std::vector::emplace_back的區別

std::vector::push_back和std::vector::emplace_back的區別

vector<T>().push_back(T(args));

相當於

vector<T>().emplace_back(args);

C++11之前,push_back先後調用了構造函數、拷貝構造函數(臨時申請堆空間,影響性能);

C++11之後,push_back先後調用了構造函數、轉移構造函數。

在C++11的基礎上,emplace_back比push_back少了一次轉移構造函數,只有構造函數。

在www.cplusplus.com的std::vector::push_back的註解中,提到參數可能被拷貝或移動(即 左值引用 或 右值引用):


Adds a new element at the end of the vector, after its current last element. The content of val is copied (or moved)to the new element.

這裡有個帖子做了性能測試,https://blog.csdn.net/yockie/article/details/52674366

大致代碼如下:

std::vector<std::string> v;
int count = 10000000; //分別for循環調用10000000次
v.reserve(count); //預分配十萬大小,排除掉分配內存的時間
// 方式一:push_back(const string&),參數是左值引用(傳統的引用)
{
// push_back string:327ms【最慢】
std::string temp("ceshi"); // 一次std::string構造函數
v.push_back(temp); // 左值引用,臨時變數的構造函數,拷貝構造
}
// 方式二:push_back(string &&), 參數是右值引用
{
// push_back move(string):213ms
std::string temp("ceshi"); // 一次std::string構造函數
v.push_back(std::move(temp)); // 右值引用,臨時變數的構造函數,拷貝構造
// push_back(string):229 ms
v.push_back(std::string("ceshi")); // 一次std::string構造函數,臨時變數的構造函數,右值引用,拷貝構造
// push_back(c string):215 ms
v.push_back("ceshi"); // 比上面兩種稍微快一點點,少了一次std::string構造函數
}
// 方式三:emplace_back(c string):122 ms【最塊】
{
v.emplace_back("ceshi"); // 只有一次構造函數,不調用拷貝構造函數,速度最快

std::vector::push_back和std::vector::emplace_back的區別

打開今日頭條,查看更多精彩圖片
喜歡這篇文章嗎?立刻分享出去讓更多人知道吧!

本站內容充實豐富,博大精深,小編精選每日熱門資訊,隨時更新,點擊「搶先收到最新資訊」瀏覽吧!


請您繼續閱讀更多來自 程序員小新人學習 的精彩文章:

golang json.Marshal interface 踩坑
解決JS外部文件 中文出現亂碼的問題

TAG:程序員小新人學習 |