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)