[C ++] performance difference in constructing shared_ptr through new and make_shared

Source: Internet
Author: User

A buddy in the company said that make_shared construction of shared_ptr is slower than new, and I am skeptical, because make_shared only allocates memory once and new needs to be allocated twice. So write a demo to test it.

Test whether optimization is enabled and optimization is disabled, and the performance after C ++ 11 is enabled.

 
# Include <string> # ifdef _ gxx_experimental_cxx0x __# include <memory> using namespace STD; # else # include <boost/shared_ptr.hpp> # include <boost/make_shared.hpp> using namespace boost; # endifclass Foo {public: typedef shared_ptr <Foo> PTR; Foo (): A (42), B (false), C (12.234) {} PRIVATE: int; bool B; float C; STD: String D ;}; const int loop_count = 100000000; int main (INT argc, char ** argv) {for (INT I = 0; I <loop_count; I ++) {# ifdef use_make_shared FOO: PTR P = make_shared <Foo> (); # else FOO: PTR P = FOO :: PTR (New Foo); # endif} return 0 ;}

 

Test data, in seconds:

  New (-O0) New (-O2) Make_shared (-O0) Make_shared (-O2)
Boost 20.324 11.969 35.527 11.999
Boost C ++ 11 18.064 9.099 35.249 5.277
Stl c ++ 11 18.928 9.127 35.588 5.276

We can see that under C ++ 03, the new and make_shared optimization options are added to achieve the same performance. If they are not added, they will suffer a lot.

In C ++ 11, due to the move semantics, O2 will cause make_shared to be nearly doubled faster than new. The results of O0 and C ++ 03 are not significantly different. To put it bluntly, the debug version is still much slower.

In addition, there is no significant difference between shared_ptr implemented by boost and STL.

The GCC version is 4.4, while the boost version is the old 1.42

No clang tests. If you are interested, refer to the following BlogspotArticleWith Clang On It.

Refer:

Http://tech-foo.blogspot.com/2012/04/experimenting-with-c-stdmakeshared.html (self-built ladder)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.