The cost of passing by shared_ptr

前端 未结 5 1364
迷失自我
迷失自我 2020-12-07 09:35

I use std::tr1::shared_ptr extensively throughout my application. This includes passing objects in as function arguments. Consider the following:

class Datas         


        
5条回答
  •  情书的邮戳
    2020-12-07 10:18

    Any object creation and destruction, especially redundant object creation and destruction, should be avoided in performance-critical applications.

    Consider what shared_ptr is doing. Not only is it creating a new object and filling it in, but it's also referencing the shared state to increment reference information, and the object itself presumably lives somewhere else completely which is going to be nightmarish on your cache.

    Presumably you need the shared_ptr (because if you could get away with a local object you wouldn't allocate one off of the heap), but you could even "cache" the result of the shared_ptr dereference:

    void fn(shared_ptr< Dataset > pds)
    {
       Dataset& ds = *pds;
    
       for (i = 0; i < 1000; ++i)
       {
          f(ds);
          g(ds);
       }
    }
    

    ...because even *pds requires hitting more memory than is absolutely necessary.

提交回复
热议问题