通过简单的包装指针C++智能指针性能和差异
C++ smart pointer performance and difference with a simple wrapped pointer
我遇到了有人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
据我所知,实际问题是:
我想知道,如果我使用自己的智能指针,unique_pointer会有什么特别的事情吗?它似乎相当沉重,至少在调试模式下它似乎做了很多事情。
unique_ptr
可能有更琐碎的函数调用或类似的东西,这些调用不会完全内联,从而导致调试模式下的性能变差。但是,正如您自己所说,在启用优化的情况下,关键时的性能是相同的。
尽管unique_ptr
是最简单的拥有智能指针来编写,但它仍然做了很多你的琐碎包装器没有做的事情:
- ,同时通过空基类优化确保无状态自定义删除程序不会使用额外的空间
- 它可以正确处理移动和复制
- 它正确地处理所有类型的转换;例如,
unique_ptr<Derived>
将隐式转换为unique_ptr<Base>
- 这是正确的
虽然大多数体面的C++程序员都可以实现一个体面的unique_ptr
,但我不认为大多数人能实现一个完全正确的。这些边缘情况会伤害你。
只需使用unique_ptr
,在关闭优化的情况下滚动自己的以获得更好的性能不是一个很好的理由。
- 介于 [固定数组] 和 [带内存分配的指针] 之间的性能
- 避免使用指针时C++的性能和安全性
- C++ 将函数指针与最佳性能相结合
- 指针和程序性能之间有什么关系吗?
- 指针保护和性能
- 性能:指针在C++中取消引用
- 在类中始终使用此指针是否有任何性能成本
- C 指针向量如何影响性能
- 比较 C/C++ 中指针分配的性能
- C++ 双指针的库达性能
- 通过简单的包装指针C++智能指针性能和差异
- 这个指针和性能惩罚
- 我们是否应该将指向类实例的智能指针存储在大型 std::vector 中以获得更好的性能?
- 局部变量与指针性能
- 对象容器的性能与指针容器的性能
- 指针向量与值向量 大内存块与小内存块的性能损失
- 为什么预分配的函数指针的性能比分支差
- static_cast指针类型的性能命中率
- 虚函数与函数指针 - 性能
- C++ 虚函数与成员函数指针(性能比较)