Home
Search
C# ListDictionaryUse the ListDictionary type, adding elements and using Count. Benchmark the type.
ListDictionary. This is a specialized C# collection. It is found in the System.Collections Specialized namespace. It is similar to Hashtable.
Hashtable
This type represents a non-generic dictionary type. It is implemented with a linked list. It may be faster for when we have many small collections.
Example. With ListDictionary, we can Add and Remove elements and use the Count property. The key difference is in its performance characteristics.
Tip In small collections, it will be faster than a Hashtable with the same data.
Version 1 This version of the code creates a ListDictionary and looks up elements from it.
Version 2 Here we do the same thing as version 1 of the code but use a Hashtable instead of a ListDictionary.
Result You can see that the ListDictionary was faster for looking up an element in a small collection. The Hashtable was slower.
using System; using System.Collections; // For Hashtable. using System.Collections.Specialized; // For ListDictionary. using System.Diagnostics; class Program { static void Main() { ListDictionary list = new ListDictionary(); list.Add("dot", 1); list.Add("net", 2); list.Add("perls", 3); Hashtable hash = new Hashtable(); hash.Add("dot", 1); hash.Add("net", 2); hash.Add("perls", 3); Console.WriteLine("ListDictionary.Count: {0}", list.Count); Console.WriteLine("Hashtable.Count: {0}", hash.Count); Console.WriteLine(); const int max = 10000000; // Version 1: use ListDictionary. var s1 = Stopwatch.StartNew(); for (int i = 0; i < max; i++) { object a = list["perls"]; } s1.Stop(); // Version 2: use Hashtable. var s2 = Stopwatch.StartNew(); for (int i = 0; i < max; i++) { object a = hash["perls"]; } s2.Stop(); Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) / max).ToString("ListDictionary: 0.00 ns")); Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000000) / max).ToString("Hashtable: 0.00 ns")); } }
ListDictionary.Count: 3 Hashtable.Count: 3 ListDictionary: 17.69 ns Hashtable: 51.14 ns
Performance notes. I have found that types in System.Collections Generic are much better overall than those in System.Collections and System.Collections Specialized.
Tip I recommend developers avoid writing new code with types such as ListDictionary and Hashtable.
And As for implementing Dictionary collections with Lists, this can be fast on small amounts of data, but will be slow on larger amounts.
List
Dictionary
Summary. The ListDictionary collection has performance benefits in certain programs. But modern types from System.Collections Generic are better in nearly all programs.
Home
© 2007-2022 sam allen.
see site info on the changelog.