您的位置:首页 > 其它

Link List VS Dynamic Array

2013-01-03 03:07 127 查看
The size of a linked list node is two machine words for a single linked list and three for a double linked list (object reference, next reference, prev reference - roughly.. I have not yet looked at the exact .NET implementation of linked list). Plus whatever
overhead the list itself needs.



The size of a dynamic array element is only the size of the object (one machine word for reference types). Plus whatever overhead the list itself needs.



Both list and array will allocate memory in chunks of X number of objects so that they don't have to allocate memory on every insertion.



Memory isn't usually the primary consideration for which object is best for your needs. It is the cost (in time) of the various operations that will determine which you use. Here are some general costs, I'll throw Dictionary in these results as well.



Insertion to the end of either array or list is about the same cost.

Insertion to an arbitrary position is much faster on a linked list.

Insertion is relatively slow on a dictionary.



Deletion at the end of either array or list is about the same cost.

Deletion at an arbitrary position is much faster on a linked list.

Deletion is relatively slow on a dictionary (if it's a balanced tree, not sure how .net implements).



Positional access is fast on an array.

Positional access is very slow on a linked list (you'd have to enumerate N times to find node at N position).

Positional access is impossible on a dictionary as element order can change.



Searching is the same for both array and linked list (slow - every element has to be looked at on failure).

Searching is relatively fast on a dictionary.



Enumeration is about the same for both linked list and array.

Enumeration on a dictionary can be a little slower as the enumerator needs a bit more state data. Keep in mind that enumeration order can change from one enumeration to the next. Not sure if .net uses a stateful enumerator or simply allocates (and copies) an
array when asked to enumerate.



Basically you can ask these questions:



Do I need to search more often then insert/delete? Use a dictionary.

Is element order important? Do not use a dictionary.

Do I need positional access? Use an array.

Do I need to insert/delete at arbitrary points? Use a linked list.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: