16

可能重复:
何时在 c# 中使用 ArrayList 而不是 array[]?

从内存或处理器成本的角度来看,数组和 arrayList 对象之间是否存在显着差异?

4

2 回答 2

7

An array is a low-level data structure that essentially maps to a region in memory. An ArrayList is a variable length list implemented as an array of object that is re-allocated as the list grows.

ArrayList therefore has some overhead related to managing the size of the internal array, and more overhead related to casting objects to the correct type when you access the list.

Also, storing everything as object means that value types get boxed on write and unboxed on read, which is extremely detrimental to performance. Using List<T>, a similar but strongly-typed variable size list avoids this issue.

In fact, ArrayList is practically deprecated in favor of List<T> since .NET 2.0.

于 2012-05-25T01:35:14.807 回答
1

An array is a contiguous block of memory of fixed size, whereas an ArrayList (though you should prefer List since .NET 2.0) wraps an array to provide dynamically-resizable storage.

The "difference" between them being that, as far as they're encapsulated, an ArrayList is resizable, an array isn't. As far as the implementation is concerned: because an ArrayList wraps (and reallocates) arrays it will require more slightly more memory than an array (as it has to know the current number of elements, as opposed to its capacity), furthermore an ArrayList also requires CPU time to reallocate and copy its internal array if it ever reaches its internal capacity.

However, instantiating an ArrayList is no more expensive than allocating an array. The only difference there being the handful of instructions needed to initialize the ArrayList's state. The difference is negligible and not worth worrying about.

You'll find that if you are reallocating an array by yourself as the means of creating a resizable collection then you're better off using ArrayList/List as it has been thoroughly tested.

于 2012-05-25T01:36:04.997 回答