小编Chr*_*ris的帖子

在C#中重用数组

因此,我正在优化一个非常频繁地使用字节数组的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 = …
Run Code Online (Sandbox Code Playgroud)

c# arrays optimization performance reusability

4
推荐指数
2
解决办法
3544
查看次数

调整List <T>的容量

我System.Collections.Generic.List<T>用Reflector 阅读了.NET4.0 类的源代码,我有一些问题.这是代码:

    [__DynamicallyInvokable]
    public void Add(T item)
    {
        if (this._size == this._items.Length)
        {
            this.EnsureCapacity(this._size + 1);
        }
        this._items[this._size++] = item;
        this._version++;
    }
    private void EnsureCapacity(int min)
    {
        if (this._items.Length < min)
        {
            int num = (this._items.Length == 0) ? 4 : (this._items.Length * 2);
            if (num > 0x7fefffff)
            {
                num = 0x7fefffff;
            }
            if (num < min)
            {
                num = min;
            }
            this.Capacity = num;
        }
    }
    [__DynamicallyInvokable]
    public int Capacity
    {
        // omitted code

        set
        { …
Run Code Online (Sandbox Code Playgroud)

c# algorithm performance memory-management list

3
推荐指数
1
解决办法
1638
查看次数