C#: Different Ways Of Iterating Over A Dictionary And Their Performance - TechNet Articles - United States (English) - TechNet Wiki


Table of Contents

C#: Different Ways Of Iterating Over A Dictionary And Their Performance



 This article discusses and evaluates the performance of three different ways of iterating over a Dictionary in C#.

The Three Different Methods of Iterating Over Dictionary

First, let's assume that the Dictionary variable is as follows:

Dictionary<int, string> profilingDictionary;

Our profilingDictionary variable contains 11,998,949 Key-Value records.

The three most popular way of iterating over Dictionary variables in your C# program are discussed below:

Method 1 (for loop, not foreach iteration)

Using old-school for loop as follows:

for (int i = 0; i < profilingDictionary.Count; i++ )
 {
 int key = i;
 string value = profilingDictionary[i];
 // Do something here
 }

Method 2 (foreach iteration, the lazy way)

Using foreach lazy coding as follows:

foreach (var entry in profilingDictionary)
 {
 int key = entry.Key;
 string value = entry.Value;
 // Do something here
 } 

Method 3 (foreach iteration, making everything right)

Using foreach non-lazy coding (statically typed) as follows:

foreach (KeyValuePair<int, string> entry in profilingDictionary)
 {
 int key = entry.Key;
 string value = entry.Value;
 // Do something here
 }

Performance Difference Between The Three Methods

After running the performance test several times, no doubt the statically typed foreach iteration over a Dictionary variable is by far the best performing out of the three. Check the following screenshot:

So Why Use Statically Typed Non-Lazy 'Foreach' Iteration Over Dictionary?

From the performance analysis, there is no doubt that performance of this way of iterating over a Dictionary variable is more efficient, but it has a bigger advantage to it. The advantage being "clean coding". By statically typing the item to be iterated you are making your code much more maintainable by anyone.

ce Difference Between The Three Methods

After running the performance test several times, no doubt the statically typed foreach iteration over a Dictionary variable is by far the best performing out of the three. Check the following screenshot:

So Why Use Statically Typed Non-Lazy 'Foreach' Iteration Over Dictionary?

From the performance analysis, there is no doubt that performance of this way of ite

Extras

The code sample for performance profiling is available to download from TechNet Gallery.

This code sample for performance profiling is also available to download on GitHub.