Question

I didn't find information about performance issues with auto_ptr and shared_ptr(I use tr1 implementation). As shared_ptr is more complicated compared to auto_ptr so auto_ptr is faster? So in general question sounds like what can you say about performance of shared_ptr with comparison with auto_ptr?

PS: I know that now unique_ptr is preferable than auto_ptr, but not all compilers support it, so question is about auto_ptr and shared_ptr

Était-ce utile?

La solution

  1. When dereferencing there are no performance differences.

  2. If you allocate your shared_ptr's with make_shared you don't waste any heap allocations.

  3. When copying the pointer (not the object), a shared_ptr is a little bit slower because it needs to increase it's reference counter.

However, these probably does not matter, so stick with shared_ptr combined with make_shared.

Autres conseils

auto_ptr is a deprecated C++98 construct. As such, any performance benefit it might have is far outweighed by the fact that you shouldn't use it anymore in newly-written C++11 code, and instead badger the compiler / library maintainers to implement support for unique_ptr.

That being said, use what semantically fits your use case, unless you have profiled that you have a problem with *_ptr...

As with all performance issues: you need to measure it for yourself in your particular setup.

In general, though, you can expect some more overhead for a shared_ptr<> than for auto_ptr<> as it has to do some more work behind the scene to ensure proper shared behavior for the enclosed pointer.

On the other hand, the two are not really comparable: auto_ptr<> supports only one copy (the ownership is transfered on copy), while shared_ptr<> supports multiple copies. So unless you only use the above pointers for one copy-pointer, you cannot make a meaningful comparision. If you do use one-copy pointer and you are sure you will not need more copies, use the specialized auto_ptr<>.

In any case, whether the performance differences are significant depends on your particular project.

In general the only good answer is to measure.

But for this case you know that shared_ptr, unless you're using make_shared it involves a dynamic allocation of a counter block, and unless you have a really good small objects allocator, it's bound to be really slow (talking orders of magnitude) to create the first shared pointer to an object.

But then, perhaps with Boost and the standard library that allocation is really optimized. And maybe, probably!, you can use make_shared to use just 1 allocation for both the object and its control block. So … measure.

By the way, auto_ptr is deprecated.

With any modern compiler use unique_ptr instead.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top