gpt4 book ai didi

c# - 在 C# 中重用数组

转载 作者:太空狗 更新时间:2023-10-30 00:40:44 24 4
gpt4 key购买 nike

所以我正在优化一个非常非常频繁地使用字节数组的 C# 程序,我写了一种回收池的东西来重用必须由 GC 收集的数组。像那样:

public class ArrayPool<T>
{
private readonly ConcurrentDictionary<int, ConcurrentBag<T[]>> _pool;

public ArrayPool()
{
_pool = new ConcurrentDictionary<int, ConcurrentBag<T[]>>();
}

public ArrayPool(int capacity)
{
_pool = new ConcurrentDictionary<int, ConcurrentBag<T[]>>(4, capacity);
for (var i = 1; i <= capacity; i++)
{
_pool.TryAdd(i, new ConcurrentBag<T[]>());
}
}

public T[] Alloc(int capacity)
{
if (capacity < 1)
{
return null;
}
if (_pool.ContainsKey(capacity))
{
var subpool = _pool[capacity];
T[] result;
if (subpool != null) return subpool.TryTake(out result) ? result : new T[capacity];
subpool = new ConcurrentBag<T[]>();
_pool.TryAdd(capacity, subpool);
_pool[capacity] = subpool;
return subpool.TryTake(out result) ? result : new T[capacity];
}
_pool[capacity] = new ConcurrentBag<T[]>();
return new T[capacity];
}

public void Free(T[] array)
{
if (array == null || array.Length < 1)
{
return;
}
var len = array.Length;
Array.Clear(array, 0, len);
var subpool = _pool[len] ?? new ConcurrentBag<T[]>();
subpool.Add(array);
}

}

我还写了一些代码来测试它的性能:

const int TestTimes = 100000;
const int PoolCapacity = 1000;
public static ArrayPool<byte> BytePool;
static void Main()
{
BytePool = = new ArrayPool<byte>(PoolCapacity);
var watch = Stopwatch.StartNew();
for (var i = 1; i <= TestTimes; i++)
{
var len = (i % PoolCapacity) + 1;
var array = new byte[len];
}
watch.Stop();
Console.WriteLine("Traditional Method: {0} ms.", watch.ElapsedMilliseconds);
watch = Stopwatch.StartNew();
for (var i = 1; i <= TestTimes; i++)
{
var len = (i % PoolCapacity) + 1;
var array = BytePool.Alloc(len);
BytePool.Free(array);
}
watch.Stop();
Console.WriteLine("New Method: {0} ms.", watch.ElapsedMilliseconds);
Console.ReadKey();
}

我认为如果程序可以重用内存而不是每次都 malloc 它们应该会更快,但事实证明我的代码比以前慢了大约 10 倍:

Traditional Method: 31 ms. New Method: 283 ms.

那么在 C# 中,resuing 数组真的可以提高性能吗?如果为真,为什么我的代码这么慢?有没有更好的方法来重用数组?

如有任何建议,我们将不胜感激。谢谢。

最佳答案

您应该查看新的 System.Buffers包。

关于c# - 在 C# 中重用数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24884281/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com