C++ std:shared_ptr自定义allocator引入内存池
ztj100 2025-01-21 23:12 21 浏览 0 评论
当C++项目里做了大量的动态内存分配与释放,可能会导致内存碎片,使系统性能降低。当动态内存分配的开销变得不容忽视时,一种解决办法是一次从操作系统分配一块大的静态内存作为内存池进行手动管理,堆对象内存分配时从内存池中分配一块类对象大小的内存,释放时并不实际将内存归还给操作系统,而是交给自定义的内存管理模块处理。本文介绍基于std::shared_ptr自定义allocator引入内存池的方法。
尝试重写new和delete运算符
项目中大量使用std::shared_ptr且与多个模块耦合, 如果直接将 std::shared_ptr 重构为手动管理裸指针的实现,改动量太大,而且可能会带来不可预料的问题。于是尝试了重写new和delete运算符并添加了打印,发现 std::shared_ptr 的创建并不会直接调用 new和 delete, 原因在于std::shared_ptr 有自己的内存分配机制。
std::allocate_shared
于是,想到了STL的一大组件 Allocator。C++提供了 std::alloc_shared 函数,可以自定义std::shared_ptr 的内存分配方式,其定义如下:
std::allocate_shared<T>(custom_alloc, std::forward<Args>(args)...);
仅需传入自定义分配器allocator和T的构造参数列表。
实际上, std::make_shared 就是对以上函数进行了封装,使用了默认的分配器。
MemoryPool的使用
内存池直接采用了相关开源项目的定义:
可以选用
https://github.com/DevShiftTeam/AppShift-MemoryPool
或
Fast Efficient Fixed-Sized Memory Pool
MemoryPoolManager 管理内存池的类
- 分配内存池
内存池需要拥有静态生命周期,因此将内存池管理类 MemoryPoolManager 设计为全局单例模式实现,定义Alloc() 和 Free() 方法,实现了内存池与自定义分配器解耦。
- 引入自旋锁实现线程安全
由于使用的相关开源内存池不是线程安全的,因此引入了自旋锁在内存池做内存分配和释放时加锁。自旋锁采用了以下文章中的实现:
Correctly implementing a spinlock in C++
MemoryPoolManager 的完整实现如下:
class MemoryPoolManager {
public:
static MemoryPoolManager& GetInstance();
void* Alloc(size_t sz);
void Free(void* p);
~MemoryPoolManager();
private:
MemoryPoolManager();
MemoryPoolManager(const MemoryPoolManager&)=delete;
MemoryPoolManager& operator=(const MemoryPoolManager&)=delete;
MemoryPool* pool_;
SpinLock spin_lock_;
};
MemoryPoolManager& MemoryPoolManager::GetInstance() {
static MemoryPoolManager instance;
return instance;
}
MemoryPoolManager::MemoryPoolManager() {
pool_ = new MemoryPool();
}
MemoryPoolManager::~MemoryPoolManager() {
std::lock_guard<SpinLock> lock(spin_lock_);
delete pool_;
}
void* MemoryPoolManager::Alloc(size_t sz) {
std::lock_guard<SpinLock> lock(spin_lock_);
return pool_->allocate(sz);
}
void MemoryPoolManager::Free(void* p) {
std::lock_guard<SpinLock> lock(spin_lock_);
pool_->free(p);
}
自定义分配器Custom Allocator
为了使用 std::alloc_shared ,还需要实现 Custom Allocator 。其中包含了需要的函数和别名定义,相关文章可参考: Building Your Own Allocators。以下接口中许多成员在C++20中被移除。
template <typename T>
class CustomAllocator {
public:
using value_type = T;
using size_type = std::size_t;
using difference_type = std::ptrdiff_t;
CustomAllocator() = default;
~CustomAllocator() = default;
template <typename U>
CustomAllocator(const CustomAllocator<U>&) noexcept {}
T* allocate(size_t n) {
return static_cast<T*>(MemoryPoolManager::GetInstance().Alloc(n * sizeof(T)));
}
void deallocate(T* p, size_t) {
MemoryPoolManager::GetInstance().Free(p);
}
size_type max_size() const noexcept {
return std::numeric_limits<size_type>::max() / sizeof(T);
}
private:
template <typename U>
friend class CustomAllocator;
};
其中T* allocate(size_t n)方法实现内存的分配, 直接调用了MemoryPoolManager的 Alloc方法;void deallocate(T* p, size_t) 做内存的释放,直接调用了MemoryPoolManager的 Free 方法。
我们知道 new操作会分配内存并会调用类的构造函数 ,那么allocate 了需要手动调用构造函数吗?
在自定义分配器中,一般不需要手动实现 construct 和 destroy,因为标准库中的 std::allocator_traits 会处理这些工作。std::allocator_traits 默认会使用 placement new 来调用对象的构造函数,并调用对象的析构函数。
相当于在CustomAllocator 中增加以下函数:
template<typename U, typename... Args>
void construct(U* p, Args&&... args) {
::new((void*)p) U(std::forward<Args>(args)...);
}
template<typename U>
void destroy(U* p) {
p->~U();
}
使用std::allocate_shared
接下来就可以使用std::allocate_shared了 ,需传入自定义分配器allocator对象和类的构造函数参数列表。仿照 std::make_shared的实现,基于可变长参数模板做了一层函数封装:
template <typename T, typename... Args>
std::shared_ptr<T> AllocateShared(Args&&... args) {
return std::allocate_shared<T>(CustomAllocator<T>(), std::forward<Args>(args)...);
}
这样,使用AllocateShared 直接就可以返回一个std::shared_ptr<Object>对象:
std::shared_ptr<Object> = AllocateShared<Object>();
实验
对这两种方法进行了对比,使用 AppShift-MemoryPool 作为内存池,一次创建N个 std::shared_ptr<object>的耗时,其中Object的大小大约2kb左右,测试结果如下,引入内存池后有明显性能提升,引入内存池后有明显性能提升,大约快了3倍:
方法\创建数量 | 1000 | 3000 |
std::shared_ptr | 1.8ms | 4.2ms |
std::alloc_shared | 0.6ms | 1.5ms |
完整代码地址
https://github.com/qiangcraft/alloc_shared/
参考
- https://docs.oracle.com/cd/E19205-01/819-3703/15_3.htm
- https://en.cppreference.com/w/cpp/memory/allocator
相关推荐
- 使用 Pinia ORM 管理 Vue 中的状态
-
转载说明:原创不易,未经授权,谢绝任何形式的转载状态管理是构建任何Web应用程序的重要组成部分。虽然Vue提供了管理简单状态的技术,但随着应用程序复杂性的增加,处理状态可能变得更具挑战性。这就是为什么...
- Vue3开发企业级音乐Web App 明星讲师带你学习大厂高质量代码
-
Vue3开发企业级音乐WebApp明星讲师带你学习大厂高质量代码下栽课》jzit.top/392/...
- 一篇文章说清 webpack、vite、vue-cli、create-vue 的区别
-
webpack、vite、vue-cli、create-vue这些都是什么?看着有点晕,不要怕,我们一起来分辨一下。...
- 超赞 vue2/3 可视化打印设计VuePluginPrint
-
今天来给大家推荐一款非常不错的Vue可拖拽打印设计器Hiprint。引入使用//main.js中引入安装import{hiPrintPlugin}from'vue-plugin-...
- 搭建Trae+Vue3的AI开发环境(vue3 ts开发)
-
从2024年2025年,不断的有各种AI工具会在自媒体中火起来,号称各种效率王炸,而在AI是否会替代打工人的话题中,程序员又首当其冲。...
- Vue中mixin怎么理解?(vue的mixins有什么用)
-
作者:qdmryt转发链接:https://mp.weixin.qq.com/s/JHF3oIGSTnRegpvE6GSZhg前言...
- Vue脚手架安装,初始化项目,打包并用Tomcat和Nginx部署
-
1.创建Vue脚手架#1.在本地文件目录创建my-first-vue文件夹,安装vue-cli脚手架:npminstall-gvue-cli安装过程如下图所示:创建my-first-vue...
- 新手如何搭建个人网站(小白如何搭建个人网站)
-
ElementUl是饿了么前端团队推出的桌面端UI框架,具有是简洁、直观、强悍和低学习成本等优势,非常适合初学者使用。因此,本次项目使用ElementUI框架来完成个人博客的主体开发,欢迎大家讨论...
- 零基础入门vue开发(vue快速入门与实战开发)
-
上面一节我们已经成功的安装了nodejs,并且配置了npm的全局环境变量,那么这一节我们就来正式的安装vue-cli,然后在webstorm开发者工具里运行我们的vue项目。这一节有两种创建vue项目...
- .net core集成vue(.net core集成vue3)
-
react、angular、vue你更熟悉哪个?下边这个是vue的。要求需要你的计算机安装有o.netcore2.0以上版本onode、webpack、vue-cli、vue(npm...
- 使用 Vue 脚手架,为什么要学 webpack?(一)
-
先问大家一个很简单的问题:vueinitwebpackprjectName与vuecreateprojectName有什么区别呢?它们是Vue-cli2和Vue-cli3创建...
- vue 构建和部署(vue项目部署服务器)
-
普通的搭建方式(安装指令)安装Node.js检查node是否已安装,终端输入node-v会使用命令行(安装)npminstallvue-cli-首先安装vue-clivueinitwe...
- Vue.js 环境配置(vue的环境搭建)
-
说明:node.js和vue.js的关系:Node.js是一个基于ChromeV8引擎的JavaScript运行时环境;类比:Java的jvm(虚拟机)...
- vue项目完整搭建步骤(vuecli项目搭建)
-
简介为了让一些不太清楚搭建前端项目的小白,更快上手。今天我将一步一步带领你们进行前端项目的搭建。前端开发中需要用到框架,那vue作为三大框架主流之一,在工作中很常用。所以就以vue为例。...
你 发表评论:
欢迎- 一周热门
- 最近发表
-
- 使用 Pinia ORM 管理 Vue 中的状态
- Vue3开发企业级音乐Web App 明星讲师带你学习大厂高质量代码
- 一篇文章说清 webpack、vite、vue-cli、create-vue 的区别
- 超赞 vue2/3 可视化打印设计VuePluginPrint
- 搭建Trae+Vue3的AI开发环境(vue3 ts开发)
- 如何在现有的Vue项目中嵌入 Blazor项目?
- Vue中mixin怎么理解?(vue的mixins有什么用)
- Vue脚手架安装,初始化项目,打包并用Tomcat和Nginx部署
- 新手如何搭建个人网站(小白如何搭建个人网站)
- 零基础入门vue开发(vue快速入门与实战开发)
- 标签列表
-
- idea eval reset (50)
- vue dispatch (70)
- update canceled (42)
- order by asc (53)
- spring gateway (67)
- 简单代码编程 贪吃蛇 (40)
- transforms.resize (33)
- redisson trylock (35)
- 卸载node (35)
- np.reshape (33)
- torch.arange (34)
- node卸载 (33)
- npm 源 (35)
- vue3 deep (35)
- win10 ssh (35)
- exceptionininitializererror (33)
- vue foreach (34)
- idea设置编码为utf8 (35)
- vue 数组添加元素 (34)
- std find (34)
- tablefield注解用途 (35)
- python str转json (34)
- java websocket客户端 (34)
- tensor.view (34)
- java jackson (34)