【无标题】对象池,大量创建对象时提高性能

文章通过示例展示了在开发中如何利用ObjectPool和ConcurrentBag来优化频繁的对象创建和销毁,从而提高程序性能。在高需求场景下,对比了使用对象池和直接创建对象的时间差异,显示了对象池在管理资源和减少垃圾回收方面的优势。
摘要由CSDN通过智能技术生成

在开发中,我们经常会遇到以下场景: 1.对象的大量创建和销毁,比如网口接收数据,进行数据解析。 2.大量对象的创建和销毁,导致性能下降。 3 循环中大量new对象

看到微软帮助中有一个ConcurrentBag的用法,挺不错的

using System;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;

namespace ObjectPoolExample
{
    public class ObjectPool<T>
    {
        private readonly ConcurrentBag<T> _objects;
        private readonly Func<T> _objectGenerator;

        public ObjectPool(Func<T> objectGenerator)
        {
            _objectGenerator = objectGenerator ?? throw new ArgumentNullException(nameof(objectGenerator));
            _objects = new ConcurrentBag<T>();
        }

        public T Get() => _objects.TryTake(out T item) ? item : _objectGenerator();

        public void Return(T item) => _objects.Add(item);
    }

    class Program
    {
        static void Main(string[] args)
        {
           var cts = new CancellationTokenSource();

            // Create an opportunity for the user to cancel.
            _ = Task.Run(() =>
            {
                if (char.ToUpperInvariant(Console.ReadKey().KeyChar) == 'C')
                {
                    cts.Cancel();
                }
            });

            var pool = new ObjectPool<ExampleObject>(() => new ExampleObject());

            Stopwatch sw = new Stopwatch();
            sw.Start();
            int nCount = 100000;

            // Create a high demand for ExampleObject instance.
            for (int i = 0; i < nCount; i++)
            {
                var example = pool.Get();
                try
                {
                   // Console.CursorLeft = 0;
                    // This is the bottleneck in our application. All threads in this loop
                    // must serialize their access to the static Console class.
                    //Console.WriteLine($"{example.GetValue(i):####.####}");
                }
                finally
                {
                    pool.Return(example);
                }
            }

            sw.Stop();
            Console.WriteLine("用时1:" + sw.ElapsedMilliseconds + "");

            sw.Start();
            for (int i = 0; i < nCount; i++)
            {
                var example = new ExampleObject();
            }
            sw.Stop();
            Console.WriteLine("用时2:" + sw.ElapsedMilliseconds + "");

        }
    }

    // A toy class that requires some resources to create.
    class ExampleObject
    {
        public int[] Nums { get; set; }

        public ExampleObject()
        {
            Nums = new int[10000];
            var rand = new Random();
            for (int i = 0; i < Nums.Length; i++)
            {
                Nums[i] = rand.Next();
            }
        }

        public double GetValue(long i) => Math.Sqrt(Nums[i]);
    }
}

对比下时间相差还是比较大的

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值