Friday, March 22, 2013

Array vs ArrayList vs Generic List vs LinkedList in .Net

Array vs ArrayList vs Generic List vs LinkedList in .Net

Arrays

Arrays cannot shrink or grow unless you copy the array to an entirely new array of a different size.  Once the size of an array is declared that is the size it must remain without heavy overhead.

Arrays can contain objects or primitives.


ArrayLists
An ArrayList uses a dynamically expanding Array internally, so there can be a performance hit when expanding past the size of its internal Array.  The size of the internal array of an array list does not change, in order to increase performance.  When an element is added beyond the capacity of the ArrayList the internal array is copied and a new array of twice the number of elements is created.  Thus reducing the need to expand the internal array for a while.  This uses more memory, but can make it perform more quickly.  Array lists also start with an internal Array with ten elements, also to reduce the need to increase its size.

ArrayLists can only contain objects.

List
List is a generic implementation of ArrayList.  ArrayList appears to be being deprecated.

LinkedList
LinkedList can have performance issues since it can cause memory fragmentation.  There is no set bounds for a LinkedList, so data in the list can end up anywhere in memory.  This can be confusing, since we also said that ArrayLists can have performance issues due to recreating the internal Array on inserts.

You have to determine when you need to gain.  Do you need to free up memory or need to have fast inserts and deletions, then LinkedList.  Do you need fast access to items and will be doing very few inserts, then perhaps Array or List is what you want.

Memory
ArrayLists can use 100s of percent more memory than List.

Types

Under the covers ArrayList is an array of type object[].  List is an array of whatever specific type T you make it.  This can allow for better memory usage and a more precise implementation in code.

Performance

Arrays and Lists allow for very fast read since they are a fix size making each piece of data stored right next to each other in memory.

LinkedList can have performance issues since it can cause memory fragmentation.  There is no set bounds for a LinkedList, so data in the list can end up anywhere in memory.


No comments: