[c++]通過new和make_shared構造shared_ptr的效能差異

來源:互聯網
上載者:User

公司一哥們說make_shared構造shared_ptr比new要慢,我表示懷疑.因為make_shared只分配一次記憶體,而new需要分配兩次.所以寫一個demo測試一下.

分別測試開啟最佳化,關閉最佳化,還有就是C++11開啟move之後的效能情況.

#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 a;        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;}

 

測試資料,時間單位均為秒:

  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

可以看出,在C++03下面,new和make_shared加了最佳化選項,才表現的一致;不加的話,會挫很多.

而C++11下面,由於有move語義,O2會導致make_shared比new快將近1倍;而O0和C++03的結果無顯著差別,說白了,debug版的還是慢很多.

另外boost實現的shared_ptr和STL實現的,無顯著差別.

gcc版本是4.4,boost版本是老的掉牙的1.42

沒有做clang的測試,有興趣可以看下面blogspot的文章,上面有clang的.

參考:

http://tech-foo.blogspot.com/2012/04/experimenting-with-c-stdmakeshared.html (自備梯子)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.