在整个应用程序中广泛使用std :: tr1 :: shared_ptr。包括作为函数参数传递对象。考虑以下:
class Dataset {...}
void f( shared_ptr< Dataset const > pds ) {...}
void g( shared_ptr< Dataset const > pds ) {...}
...
虽然通过shared_ptr传递一个数据集对象保证了它在f和g中的存在,但这些函数可能被调用了数百万次,导致大量的shared_ptr对象被创建和销毁。以下是最近一次运行的平面gprof配置文件的一部分:
Each sample counts as 0.01 seconds.
% cumulative self self total
time seconds seconds calls s/call s/call name
9.74 295.39 35.12 2451177304 0.00 0.00 std::tr1::__shared_count::__shared_count(std::tr1::__shared_count const&)
8.03 324.34 28.95 2451252116 0.00 0.00 std::tr1::__shared_count::~__shared_count()
因此,约17%的运行时间用于使用shared_ptr对象的引用计数。这是正常的吗?
我的应用程序的很大一部分是单线程的,我正考虑重写一些函数
void f( const Dataset& ds ) {...}
并更换调用
shared_ptr< Dataset > pds( new Dataset(...) );
f( pds );
同
f( *pds );
在我知道的地方,当程序的流程在f()内时,对象不会被破坏。但在我改变一堆函数调用之前,我想知道通过shared_ptr传递的典型性能是什么。看起来像shared_ptr不应该用于经常被调用的函数。
发布于 2018-05-14 18:10:39
总是传递shared_ptr
的const引用:
void f(const shared_ptr<Dataset const>& pds) {...}
void g(const shared_ptr<Dataset const>& pds) {...}
关于他人提到的安全问题:
shared_ptr
在整个应用程序中大量使用时,传递值将占用大量时间(我已经看到它超过50 +%)。const T&
而不是const shared_ptr<T const>&
。const shared_ptr<T const>&
比const T*
性能成问题更安全。发布于 2018-05-14 19:40:57
只需要shared_ptr将其传递给保留以备将来使用的函数/对象。例如某些类可能会保留shared_ptr以便在工作线程中使用。对于简单的同步调用使用普通指针或引用就足够了。shared_ptr不应该使用纯指针完全替换。
https://stackoverflow.com/questions/-100008466
复制相似问题