当前位置: 首页 > news >正文

Unity C# 引用池 ReferencePool

Unity C# 引用池 ReferencePool

1.目的

对于多次创建的数据使用new 关键字是十分消耗性能的,使用完成后由GC去自动释放,当一个类型的数据频繁创建可以使用引用池进行管理。

2.实现

项目目录
在这里插入图片描述

IReference 接口

要放入引用池的数据只需要继承这个接口即可

namespace ReferencePool
{public interface IReference{void Clear();}
}

ReferenceCollection 引用集合

一个类型对应一个引用集合,每次请求从引用集合的队列中获取

namespace ReferencePool
{public class ReferenceCollection{private readonly Queue<IReference> m_References = new Queue<IReference>();private Type m_ReferenceType;private int m_CurrUsingRefCount;//当前引用的数量private int m_AcquireRefCount;//请求引用的总数量private int m_ReleaseRefCount;//释放引用的总数量private int m_AddRefCount;//添加引用的总数量private int m_RemoveRefCount;//移除引用的总数量public int CurrUsingRefCount => m_CurrUsingRefCount;public int AcquireRefCount => m_AcquireRefCount;public int ReleaseRefCount => m_ReleaseRefCount;public int AddRefCount => m_AddRefCount;public int RemoveRefCount => m_RemoveRefCount;public ReferenceCollection(Type refType){m_ReferenceType = refType;m_CurrUsingRefCount = 0;m_AcquireRefCount = 0;m_ReleaseRefCount = 0;m_AddRefCount = 0;m_RemoveRefCount = 0;}public T Acquire<T>() where T : class, IReference, new(){if (typeof(T) != m_ReferenceType){throw new Exception("类型不相同无法请求!!!");}m_CurrUsingRefCount++;m_AcquireRefCount++;lock (m_References){if (m_References.Count > 0){return (T)m_References.Dequeue();}}m_AddRefCount++;return new T();}public void Release(IReference reference){reference.Clear();lock (m_References){if (m_References.Contains(reference)){throw new Exception("引用已经被释放,请勿重新释放!!!");}m_References.Enqueue(reference);}m_CurrUsingRefCount--;m_ReleaseRefCount++;}public void Add<T>(int count) where T : class, IReference, new(){if (typeof(T) != m_ReferenceType){throw new Exception("类型不相同无法添加!!!");}lock (m_References){m_AddRefCount += count;while (count-- > 0){m_References.Enqueue(new T());}}}public void Remove(int count){lock (m_References){if(count > m_References.Count){count = m_References.Count;}m_RemoveRefCount += count;while (count-- > 0){m_References.Dequeue();}}}public void RemoveAll(){lock (m_References){m_RemoveRefCount += m_References.Count;m_References.Clear();}}}
}

ReferencePool 真正的引用池

对引用集合进行统一管理

public static class ReferencePool{private static readonly Dictionary<Type,ReferenceCollection> m_ReferenceCollections = new Dictionary<Type,ReferenceCollection>();public static int Count => m_ReferenceCollections.Count;//获取引用池的数量public static void ClearAll(){lock (m_ReferenceCollections){foreach (var reference in m_ReferenceCollections.Values){reference.RemoveAll();}m_ReferenceCollections.Clear();}}public static T Acquire<T>() where T : class, IReference, new(){return GetReferenceCollection(typeof(T)).Acquire<T>();}public static void Release(IReference reference){GetReferenceCollection(reference.GetType()).Release(reference);}public static void Add<T>(int count) where T : class, IReference, new(){GetReferenceCollection(typeof(T)).Add<T>(count);}public static void Remove<T>(int count) where T : class, IReference, new(){GetReferenceCollection(typeof(T)).Remove(count);}public static void RemoveAll<T>() where T : class, IReference, new(){GetReferenceCollection(typeof(T)).RemoveAll();}private static ReferenceCollection GetReferenceCollection(Type type){if (type == null){throw new Exception("Type 类型 为空!!!");}ReferenceCollection referenceCollection = null;lock (m_ReferenceCollections){if(!m_ReferenceCollections.TryGetValue(type,out referenceCollection)){referenceCollection = new ReferenceCollection(type);m_ReferenceCollections.Add(type, referenceCollection);}}return referenceCollection;}public static int GetCurrUsingRefCount<T>() where T : class, IReference, new(){return GetReferenceCollection(typeof(T)).CurrUsingRefCount;}public static int GetAcquireRefCount<T>() where T : class, IReference, new(){return GetReferenceCollection(typeof(T)).AcquireRefCount;}public static int GetReleaseRefCount<T>() where T : class, IReference, new(){return GetReferenceCollection(typeof(T)).ReleaseRefCount;}public static int GetAddRefCount<T>() where T : class, IReference, new(){return GetReferenceCollection(typeof(T)).AddRefCount;}public static int GetRemoveRefCount<T>() where T : class, IReference, new(){return GetReferenceCollection(typeof(T)).RemoveRefCount;}}

3.测试

namespace ReferencePool
{public class Program{static void Main(string[] args){TeacherData teacherData1 = ReferencePool.Acquire<TeacherData>();teacherData1.Name = "zzs";teacherData1.Age = 20;ReferencePool.Release(teacherData1);TeacherData teacherData2 = ReferencePool.Acquire<TeacherData>();teacherData1.Name = "xxx";teacherData1.Age = 18;Console.WriteLine(ReferencePool.GetCurrUsingRefCount<TeacherData>());Console.WriteLine(ReferencePool.GetAcquireRefCount<TeacherData>());Console.WriteLine(ReferencePool.GetReleaseRefCount<TeacherData>());Console.WriteLine(ReferencePool.GetAddRefCount<TeacherData>());Console.WriteLine(ReferencePool.GetRemoveRefCount<TeacherData>());Console.ReadKey();}}public class TeacherData : IReference{public string Name;public int Age;public void Clear(){Name = string.Empty;Age = 0;}}
}

4.总结

重复使用的对象只创建有限次,避免来回实例化对象的开销

相关文章:

Unity C# 引用池 ReferencePool

Unity C# 引用池 ReferencePool 1.目的 对于多次创建的数据使用new 关键字是十分消耗性能的&#xff0c;使用完成后由GC去自动释放&#xff0c;当一个类型的数据频繁创建可以使用引用池进行管理。 2.实现 项目目录 IReference 接口 要放入引用池的数据只需要继承这个接口…...

opencv 进阶10-人脸识别原理说明及示例-cv2.CascadeClassifier.detectMultiScale()

人脸识别是指程序对输入的人脸图像进行判断&#xff0c;并识别出其对应的人的过程。人脸识别程 序像我们人类一样&#xff0c;“看到”一张人脸后就能够分辨出这个人是家人、朋友还是明星。 当然&#xff0c;要实现人脸识别&#xff0c;首先要判断当前图像内是否出现了人脸&…...

〔013〕Stable Diffusion 之 图片自动评分和不健康内容过滤器 篇

✨ 目录 🎈 下载咖啡美学评价插件🎈 咖啡美学评价使用🎈 不健康内容过滤器插件🎈 下载咖啡美学评价插件 想让系统帮你的图片作品打分评价,可以下载咖啡美学自动评价插件插件地址:https://github.com/p1atdev/stable-diffusion-webui-cafe-aesthetic也可以通过扩展列表…...

6.RocketMQ之消费索引文件ConsumeQueue

功能&#xff1a;作为CommitLog文件的索引文件。 本文着重分析为consumequeue/topic/queueId目录下的索引文件。 1.ConsumeQueueStore public class ConsumeQueueStore {protected final ConcurrentMap<String>, ConcurrentMap<Integer>, ConsumeQueueInterface…...

Appium-移动端自动测试框架,如何入门?

Appium是一个开源跨平台移动应用自动化测试框架。 既然只是想学习下Appium如何入门&#xff0c;那么我们就直奔主题。文章结构如下&#xff1a; 1、为什么要使用Appium&#xff1f; 2、如何搭建Appium工具环境?(超详细&#xff09; 3、通过demo演示Appium的使用 4、Appium如何…...

复数混频器、零中频架构和高级算法开发

文章里讲解了关于射频IQ调制器、零中频架构相关的原理及技术&#xff0c;全都是干货&#xff01;其实好多同行对软件无线电的原理、IQ调制、镜像抑制都是一知半解&#xff0c;知其然不知其所以然。好好研读这篇文章&#xff0c;相信会让你有种恍然大悟的感觉。 RF工程常被视为…...

Web 拦截器-interceptor

拦截器是一种动态拦截方法调用的机制&#xff0c;类似于过滤器&#xff0c;是Spring框架提出的&#xff0c;用来动态拦截控制器方法的执行。 其作用是拦截请求&#xff0c;在指定方法调用前后&#xff0c;根据业务执行预设代码。 实现步骤 1.定义拦截器&#xff0c;实现Handl…...

Java进阶(4)——结合类加载JVM的过程理解创建对象的几种方式:new,反射Class,克隆clone(拷贝),序列化反序列化

目录 引出类什么时候被加载JVM中创建对象几种方式1.new 看到new : new Book()2.反射 Class.forName(“包名.类名”)如何获取Class对象【反射的基础】案例&#xff1a;连接数据库方法 3.克隆&#xff08;拷贝&#xff09;clone浅拷贝深拷贝案例 序列化和反序列化对象流-把对象存…...

扩散模型实战(四):从零构建扩散模型

推荐阅读列表&#xff1a; 扩散模型实战&#xff08;一&#xff09;&#xff1a;基本原理介绍 扩散模型实战&#xff08;二&#xff09;&#xff1a;扩散模型的发展 扩散模型实战&#xff08;三&#xff09;&#xff1a;扩散模型的应用 本文以MNIST数据集为例&#xff0c;从…...

YOLOv5、YOLOv8改进:S2注意力机制

目录 1.简介 2.YOLOv5改进 2.1增加以下S2-MLPv2.yaml文件 2.2common.py配置 2.3yolo.py配置 1.简介 S2-MLPv2注意力机制 最近&#xff0c;出现了基于 MLP 的视觉主干。与 CNN 和视觉Transformer相比&#xff0c;基于 MLP 的视觉架构具有较少的归纳偏差&#xff0c;在图像识…...

LeetCode 542. 01 Matrix【多源BFS】中等

本文属于「征服LeetCode」系列文章之一&#xff0c;这一系列正式开始于2021/08/12。由于LeetCode上部分题目有锁&#xff0c;本系列将至少持续到刷完所有无锁题之日为止&#xff1b;由于LeetCode还在不断地创建新题&#xff0c;本系列的终止日期可能是永远。在这一系列刷题文章…...

使用open cv进行角度测量

使用open cv进行角度测量 用了一点初中数学的知识&#xff0c;准确度&#xff0c;跟鼠标点的准不准有关系&#xff0c;话不多说直接上代码 import cv2 import mathpath "test.jpg" img cv2.imread(path) pointsList []def mousePoint(event, x, y, flags, param…...

java 线程池实现多线程处理list数据

newFixedThreadPool线程池实现多线程 List<PackageAgreementEntity> entityList new CopyOnWriteArrayList<>();//多线程 10个线程//int threadNum 10;int listSize 300;List<List<PackageAgreementDto>> splitData Lists.partition(packageAgre…...

Centos安装Docker

Centos安装 Docker 从 2017 年 3 月开始 docker 在原来的基础上分为两个分支版本: Docker CE 和 Docker EE。 Docker CE 即社区免费版&#xff0c;Docker EE 即企业版&#xff0c;强调安全&#xff0c;但需付费使用。 本文介绍 Docker CE 的安装使用。 移除旧的版本&#x…...

Unity启动项目无反应的解决

文章首发见博客&#xff1a;https://mwhls.top/4803.html。 无图/格式错误/后续更新请见首发页。 更多更新请到mwhls.top查看 欢迎留言提问或批评建议&#xff0c;私信不回。 摘要&#xff1a;通过退还并重新载入许可证以解决Unity项目启动无反应问题。 场景 Unity Hub启动项目…...

2.3 opensbi: riscv: opensbi源码解析

文章目录 3. sbi_init()函数4. init_coldboot()函数4.1 sbi_scratch_init()函数4.2 sbi_domain_init()函数4.3 sbi_scratch_alloc_offset()函数4.4 sbi_hsm_init()函数4.5 sbi_platform_early_init()函数3. sbi_init()函数 函数位置:lib/sbi/sbi_init.c函数参数:scratch为每个…...

点破ResNet残差网络的精髓

卷积神经网络在实际训练过程中&#xff0c;不可避免会遇到一个问题&#xff1a;随着网络层数的增加&#xff0c;模型会发生退化。    换句话说&#xff0c;并不是网络层数越多越好&#xff0c;为什么会这样&#xff1f; 不是说网络越深&#xff0c;提取的特征越多&#xff…...

Ubuntu服务器service版本初始化

下载 下载路径 官网&#xff1a;https://cn.ubuntu.com/ 下载路径&#xff1a;https://cn.ubuntu.com/download 服务器&#xff1a;https://cn.ubuntu.com/download/server/step1 点击下载&#xff08;22.04.3&#xff09;&#xff1a;https://cn.ubuntu.com/download/server…...

re学习(33)攻防世界-secret-galaxy-300(脑洞题)

下载压缩包&#xff1a; 下载链接&#xff1a;https://adworld.xctf.org.cn/challenges/list 参考文章&#xff1a;攻防世界逆向高手题之secret-galaxy-300_沐一 林的博客-CSDN博客 发现这只是三个同一类型文件的三个不同版本而已&#xff0c;一个windows32位exe&#xff0…...

Mybatis Plus中使用LambdaQueryWrapper进行分页以及模糊查询对比传统XML方式进行分页

传统的XML分页以及模糊查询操作 传统的XML方式只能使用limit以及offset进行分页&#xff0c;通过判断name和bindState是否为空&#xff0c;不为空则拼接条件。 List<SanitationCompanyStaff> getSanitationStaffInfo(Param("name") String name,Param("bi…...

【HTTP三个基础问题】

面试官您好&#xff01;HTTP是超文本传输协议&#xff0c;是互联网上客户端和服务器之间传输超文本数据&#xff08;比如文字、图片、音频、视频等&#xff09;的核心协议&#xff0c;当前互联网应用最广泛的版本是HTTP1.1&#xff0c;它基于经典的C/S模型&#xff0c;也就是客…...

九天毕昇深度学习平台 | 如何安装库?

pip install 库名 -i https://pypi.tuna.tsinghua.edu.cn/simple --user 举个例子&#xff1a; 报错 ModuleNotFoundError: No module named torch 那么我需要安装 torch pip install torch -i https://pypi.tuna.tsinghua.edu.cn/simple --user pip install 库名&#x…...

Python Ovito统计金刚石结构数量

大家好,我是小马老师。 本文介绍python ovito方法统计金刚石结构的方法。 Ovito Identify diamond structure命令可以识别和统计金刚石结构,但是无法直接输出结构的变化情况。 本文使用python调用ovito包的方法,可以持续统计各步的金刚石结构,具体代码如下: from ovito…...

搭建DNS域名解析服务器(正向解析资源文件)

正向解析资源文件 1&#xff09;准备工作 服务端及客户端都关闭安全软件 [rootlocalhost ~]# systemctl stop firewalld [rootlocalhost ~]# setenforce 0 2&#xff09;服务端安装软件&#xff1a;bind 1.配置yum源 [rootlocalhost ~]# cat /etc/yum.repos.d/base.repo [Base…...

深入浅出Diffusion模型:从原理到实践的全方位教程

I. 引言&#xff1a;生成式AI的黎明 – Diffusion模型是什么&#xff1f; 近年来&#xff0c;生成式人工智能&#xff08;Generative AI&#xff09;领域取得了爆炸性的进展&#xff0c;模型能够根据简单的文本提示创作出逼真的图像、连贯的文本&#xff0c;乃至更多令人惊叹的…...

Docker拉取MySQL后数据库连接失败的解决方案

在使用Docker部署MySQL时&#xff0c;拉取并启动容器后&#xff0c;有时可能会遇到数据库连接失败的问题。这种问题可能由多种原因导致&#xff0c;包括配置错误、网络设置问题、权限问题等。本文将分析可能的原因&#xff0c;并提供解决方案。 一、确认MySQL容器的运行状态 …...

客户案例 | 短视频点播企业海外视频加速与成本优化:MediaPackage+Cloudfront 技术重构实践

01技术背景与业务挑战 某短视频点播企业深耕国内用户市场&#xff0c;但其后台应用系统部署于东南亚印尼 IDC 机房。 随着业务规模扩大&#xff0c;传统架构已较难满足当前企业发展的需求&#xff0c;企业面临着三重挑战&#xff1a; ① 业务&#xff1a;国内用户访问海外服…...

记一次spark在docker本地启动报错

1&#xff0c;背景 在docker中部署spark服务和调用spark服务的微服务&#xff0c;微服务之间通过fegin调用 2&#xff0c;问题&#xff0c;docker容器中服务器来后&#xff0c;注册中心都有&#xff0c;调用服务也正常&#xff0c;但是调用spark启动任务后报错&#xff0c;报错…...

timestamp时间戳转换工具

作为一名程序员&#xff0c;一款高效的 在线转换工具 &#xff08;在线时间戳转换 计算器 字节单位转换 json格式化&#xff09;必不可少&#xff01;https://jsons.top 排查问题时非常痛的点: 经常在秒级、毫秒级、字符串格式的时间单位来回转换&#xff0c;于是决定手撸一个…...

ubuntu系统 | docker+dify+ollama+deepseek搭建本地应用

1、docker 介绍与安装 docker安装:1、Ubuntu系统安装docker_ubuntu docker run-CSDN博客 docker介绍及镜像源配置:2、ubuntu系统docker介绍及镜像源和仓库配置-CSDN博客 docker常用命令:3、ubuntu系统docker常用命令-CSDN博客 docker compose安装:4、docker compose-CS…...