Significant differences in Array vs Array List? [duplicate]

大兔子大兔子 提交于 2019-12-20 11:53:34

问题


Possible Duplicate:
When to use ArrayList over array[] in c#?

From the perspective of memory or processor costs, does there appear to be a significant difference between an array and an arrayList object?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/10747384/significant-differences-in-array-vs-array-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!