數組池減少GC工作
?????????通過ArrayPool類(名稱空間System.Buffers)使用數組池,可減少垃圾收集器的工作,ArrayPool管理一個數組池,數組可以從這租借,并返回池中,內存在ArrayPool中管理。
創建ArrayPool<T>,調用靜態Create()方法;
使用預定義共享池,通過訪問Shared屬性;
從池中租用內存,可調用Rent()方法,(池中數組元素數量最低16,且都是成倍增加);
內存(數組)返回到池中,調用Return()方法,可指定返回池之前是否清除該數組(false,下次租用數組的人可讀取數據);
ArrayPool<int> arrayPool = ArrayPool<int>.Create(maxArrayLength: 100, maxArraysPerBucket: 10);
int[] arr = ArrayPool<int>.Shared.Rent(10);
arr[15] = 15;
Console.WriteLine($"Len={arr.Length}\tarr[15]={arr[15]}");//輸出Len=16 arr[15]=15
ArrayPool<int>.Shared.Return(arr,true);
Console.WriteLine(arr[15]);//輸出0