Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

emplace/emplace_back replace insert/push_back for pair #1504

Merged
merged 2 commits into from
Aug 6, 2021

Conversation

guodongxiaren
Copy link
Member

emplace/emplace_back 替换掉push_back(std::make_pair(,))/insert(std::make_pair(,))

emplace的性能略好于push_back(T&&) 和 insert(T&&)
并且代码也更简洁

可以参考:
Effective modern C++ item 42: Consider emplacement instead of insertion.

@guodongxiaren
Copy link
Member Author

@zyearn

@guodongxiaren
Copy link
Member Author

@zyearn

这个PR有空也看下

@zyearn
Copy link
Member

zyearn commented Aug 5, 2021

还在看,这章后面也说:With current implementations of the Standard Library,
there are situations where, as expected, emplacement outperforms insertion, but,
sadly, there are also situations where the insertion functions run faster.
... to determine whether emplacement or insertion runs faster, benchmark them both.

所以还需要评估下

@guodongxiaren
Copy link
Member Author

他那段应该说的是插入已存在对象的时候,已经具名的对象。emplace是否总是优于insert是理论上的,实践上不一定。

但是前文提到如果是针对需要插入并构造新对象的时候,emplace是比insert高效的,因为emplace是传入的构造参数列表,它原地构造对象。而insert是构造临时对象,最后再move过去,然后析构临时对象。emplace没有创建和析构临时对象的开销。

我这里修改的都是构造了临时pair对象的地方

@cdjingit
Copy link
Contributor

cdjingit commented Aug 6, 2021

LGTM

@zyearn
Copy link
Member

zyearn commented Aug 6, 2021

他那段应该说的是插入已存在对象的时候,已经具名的对象。emplace是否总是优于insert是理论上的,实践上不一定。

但是前文提到如果是针对需要插入并构造新对象的时候,emplace是比insert高效的,因为emplace是传入的构造参数列表,它原地构造对象。而insert是构造临时对象,最后再move过去,然后析构临时对象。emplace没有创建和析构临时对象的开销。

我这里修改的都是构造了临时pair对象的地方

好的

@zyearn zyearn merged commit ced4c70 into apache:master Aug 6, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

3 participants