Reputation: 13948
I came across this test that someone did on C++ smart pointers, and I was wondering a couple of things. First of all, I've heard that make_shared and make_unique are faster than normal construction of a shared or unique pointer. But my results and the results of the guy who created the test showed that make_unique and make_shared are slightly slower (probably nothing significant). But I was also wondering, in debug mode for me a unique_pointer is about 3 times slower than normal pointers, and indeed also much slower than a simply wrapping a pointer in a class myself. In release mode the raw pointers, my wrapped class and unique_ptrs were roughly the same. I was wondering, does the unique_pointer do anything special that I would lose if I used my own smart pointer? It seems to be rather heavy, well at least in debug mode it seems to be doing a lot. The test is below:
#include <chrono>
#include <iostream>
#include <memory>
static const long long numInt = 100000000;
template <typename T>
struct SmartPointer
{
SmartPointer(T* pointee) : ptr(pointee) {}
T* ptr;
~SmartPointer() { delete ptr; }
};
int main() {
auto start = std::chrono::system_clock::now();
for (long long i = 0; i < numInt; ++i) {
//int* tmp(new int(i));
//delete tmp;
//SmartPointer<int> tmp(new int(i));
//std::shared_ptr<int> tmp(new int(i));
//std::shared_ptr<int> tmp(std::make_shared<int>(i));
//std::unique_ptr<int> tmp(new int(i));
//std::unique_ptr<int> tmp(std::make_unique<int>(i));
}
std::chrono::duration<double> dur = std::chrono::system_clock::now() - start;
std::cout << "time native: " << dur.count() << " seconds" << std::endl;
system("pause");
}
The link where I found this is at http://www.modernescpp.com/index.php/memory-and-performance-overhead-of-smart-pointer
Upvotes: 2
Views: 1438
Reputation: 17704
As best I can tell, the actual question is:
I was wondering, does the unique_pointer do anything special that I would lose if I used my own smart pointer? It seems to be rather heavy, well at least in debug mode it seems to be doing a lot.
It is possible that unique_ptr
may have more trivial function calls or something like that, which doesn't get fully inlined, leading to worse performance in debug mode. However, as you said yourself, the performance when it matters, with optimizations enabled, is the same.
Even though unique_ptr
is the simplest owning smart pointer to write, it still does a lot of things that your trivial wrapper does not:
unique_ptr<Derived>
will implicitly convert to unique_ptr<Base>
Although most decent C++ programmers can implement a decent unique_ptr
, I don't think most can implement one that is fully correct. And those edge cases will hurt you.
Just use unique_ptr
, rolling your own for better performance with optimizations off is not a good reason.
Upvotes: 9