日期:2014-05-18  浏览次数:21206 次

C#中 Queue是连续内存吗?
我看了MSDN感觉好像是连续内存
不过我感觉像Stack Queue这种集合,为什么要用连续内存呢?
如果用非连续内存效率应该会高一些啊?
不理解,求问

另外,Queue中的TrimExcess是什么意思啊?我看MSDN上的解释,没看懂!


------解决方案--------------------
Queue先进先出,一般元素个数不多,使用连续内存更节省空间,
------解决方案--------------------
from msdn

Queue<T> 的容量是指 Queue<T> 可以容纳的元素数。 当向 Queue<T> 添加元素时,将通过重新分配内部数组,根据需要自动增大容量。 可通过调用 TrimExcess 来减少容量。 

这说明它的确是连续的。不过对于引用类型,这关系不大。
------解决方案--------------------
可以看看压入和弹出队列元素时的源代码
C# code
public void Enqueue(T item)
{
    if (this._size == this._array.Length)
    {
        int capacity = (int) ((this._array.Length * 200L) / 100L);
        if (capacity < (this._array.Length + 4))
        {
            capacity = this._array.Length + 4;
        }
        this.SetCapacity(capacity);
    }
    this._array[this._tail] = item;
    this._tail = (this._tail + 1) % this._array.Length;
    this._size++;
    this._version++;
}

public T Dequeue()
{
    if (this._size == 0)
    {
        ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EmptyQueue);
    }
    T local = this._array[this._head];
    this._array[this._head] = default(T);
    this._head = (this._head + 1) % this._array.Length;
    this._size--;
    this._version++;
    return local;
}