C#中设计一个 ListPool 的方案
2021-03-06 16:29
                         标签:mem   min   void   lock   aci   dex   最大   sys   ack    1、回顾一下有关List的几个知识点。     点1: 注意理解 Capacity 与 Count 的不同之处。     点2: 执行 TrimExcess() 方法可将容量设置为 List 中元素的实际数目。     点3: List的 Capacity (注意理解与 Count 的不同之处)扩充是以 4 的倍数来扩充的。     点4: 执行完 Clear() 方法后,Capacity 是不会变化的。 2、ListPool方案: C#中设计一个 ListPool 的方案 标签:mem   min   void   lock   aci   dex   最大   sys   ack    原文地址:https://www.cnblogs.com/luguoshuai/p/12859369.html1 Listint> list = new Listint>();
2 Console.WriteLine(list.Capacity);   // 0
3 list.Add(1);
4 Console.WriteLine(list.Capacity);   // 4
  1 using System;
  2 using System.Collections.Generic;
  3 
  4 public interface IListPoolBase
  5 {
  6     void DoClear(int nowSeconds);
  7 }
  8 
  9 public class ListPoolItem
> pool;      //用List而不用Stack是因为在回收的时候,当pool达到上限的时候,要替换到 Capacity 最大的那个,用 Stack 无法自主替换
 13     public int lastUsedSeconds;
 14 
 15     public ListPoolItem(int initSize)
 16     {
 17         lastUsedSeconds = (int)(DateTime.Now.Ticks / TimeSpan.TicksPerSecond);
 18         pool = new List
>(initSize);
 19     }
 20 
 21     //长时间不用,清理一下池子
 22     public void DoClear(int nowSeconds)
 23     {
 24         if (pool.Count > 0)
 25         {
 26             int durationNotUse = nowSeconds - lastUsedSeconds;
 27             if (durationNotUse >= intervalTime)
 28             {
 29                 pool.Clear();
 30             }
 31         }
 32     }
 33 
 34     public void Use()
 35     {
 36         lastUsedSeconds = (int)(DateTime.Now.Ticks / TimeSpan.TicksPerSecond);
 37     }
 38 }
 39 
 40 public static class ListPool
> pool = poolItem.pool;
 57             int poolSize = pool.Count;
 58             if (poolSize > 0)
 59             {
 60                 List
> pool = poolItem.pool;
 78             List