20 June 2011

Choose the right collection type for your needs in dotnet framework

Choose the right collection type for your needs,

-when you are not concerned about the order of the items in the collections, your first inclination should be to use a System.Collections.Generic.Dictionary

-The three basic operations (Add, Remove, and Contains) all operate quickly even if the collection contains millions of items.

-Using the new LinkedList collection can potentially help you improve performance in scenarios where you need to maintain order yet still achieve fast inserts.

-Unlike List, LinkedList is implemented as a chain of dynamically allocated objects.

-The downside of a linked list from a performance point of view is increased activity by the garbage collector as it has to traverse the entire list to make sure objects were not disposed of.
-Inserting an item into a LinkedList is much faster than doing so into a List

-Dictionary may be most appropriate. However, lookup is only fast in the average case, and certain datasets could cause that performance to degrade quickly.

-SortedDictionary, uses a balanced tree implementation as the underlying data store; this provides relatively fast lookups and maintains items in a sorted order but insertions will most likely be slower (and will vary based on the number of items in the collection)

-Alternatively, you can also use SortedList, which uses two separate arrays to maintain the keys and the values separately and to maintain them both in order (in the worse case you would have to shift all the keys and values).

Custom Collections

-In certain situations, you may not find that all of your requirements are implemented in any of the existing collection types in the Framework.

-It may be that you have a unique set of requirements or that you can still use an existing collection with minor changes.

If you decide you want to write a custom collection, you should first look into extending an existing collection type.

System.Collections.ObjectModel namespace.

These collections already implement the most needed interfaces and give you the baseline functionality you expect.

1 comment:

  1. Check this for Collections in msdn



Comments Welcome