【发布时间】:2017-09-04 16:30:28
【问题描述】:
我遇到了有人在 C++ 智能指针上进行的这个测试,我想知道一些事情。首先,我听说 make_shared 和 make_unique 比共享或唯一指针的正常构造更快。但是我的结果和创建测试的人的结果表明 make_unique 和 make_shared 稍微慢一些(可能没什么大不了的)。但我也想知道,在我的调试模式下,unique_pointer 比普通指针慢大约 3 倍,而且实际上也比我自己简单地将指针包装在一个类中慢得多。在发布模式下,原始指针、我的包装类和 unique_ptrs 大致相同。我想知道,如果我使用自己的智能指针,unique_pointer 是否会做任何我会丢失的特殊操作?它似乎相当沉重,至少在调试模式下它似乎做了很多。测试如下:
#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");
}
我找到这个的链接是 http://www.modernescpp.com/index.php/memory-and-performance-overhead-of-smart-pointer
【问题讨论】:
-
"在调试模式下"你永远不应该永远在调试模式下衡量和推理性能。
-
内存分配成本将使任何分配成本相形见绌。此测试无效。
-
shared_ptr进行线程安全引用计数,而其他指针不这样做,因此预计会更慢。 -
在我看来,速度并不是
make_函数的重点。安全是。make_比普通的new和存储更好地处理失败案例。 -
如果我们从问题中删除所有不相关的数据(提到未优化的构建及其性能),还剩下什么?
标签: c++ shared-ptr smart-pointers unique-ptr