C# Generic Collections - developed.be

  • Published:November 8th, 2012
  • Category:C#

As an alternative to arrays in C#, the MS-programmers use “generic collections”; some kind of an array where the value could be any kind of object. There are 3 big types of generic collections: lists, hashsets and dictionaries. This article is about when you use which type of generic collection, based on own experiences and literature.

List

A list is ideal for all kinds of collections with less than 5 elements.

A list is fast in adding elements, but exponentially slow in searching for elements. The more elements, the slower a search will be.

For searching elements, always use Find() (Find() is up to 3x as fast as First(), and First() is about 1,5x as fast as Single()).

Elements in a list maintain an order (= enumerable)

Dictionary

A dictionary has a key/value principle, like an array.

Searching for keys is faster than searching for values. Arrange your dictionary that the key value is what you search for. If you need to search for both (keys and values), it’s best to maintain two identical dictionaries, but in the second dictionary, the keys and values are switched.

The creation is slower than the creation of a List.

Every key must be unique.

Searching keys in a Dictionary is up to 3x as fast than searching in a Lists (if the List is bigger than 5 elements). The size of a dictionary doesn’t make the search significantly slower.

A Dictionary is slower to add an element to than a List.

Elements in a Dictionary maintain an order (= enumerable)

Use dictionaries for big lists where searching for elements is more important than adding elements.

To get a value from a key, TryGetValue() is the fastest.

Hashset

A hashset doesn’t maintain order (= not enumerable). This is different from a Dictionary and a List.

Use a hashset when you want to check if an element is in a list (with “Contains”).

Use a hashset when your list could contain thousands of elements.

Hashsets, like Dictionaries, use the GetHashCode() method of an object to check if it’s unique. If you constructed a hashset with your own objects, you have to make sure the object contains a GetHashCode() override (to check if it’s unique).

In short

List (< 5 elements)List (> 5 elements)DictionaryHashset
Adding elementsFastestFasterSlower
Searching elementsFastest(Very) slow (exp.)FastFaster
Enumerable
(maintains order, loop-able)
YesYesYesNo
Ideal size<5<51000x1000x

Rss Comments

Comments

No comments yet.

Leave a comment