This article discusses and evaluates the performance of three different ways of iterating over a Dictionary in C#.
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:
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
}
Using foreach lazy coding as follows:
foreach
(var entry
in
profilingDictionary)
{
int
key = entry.Key;
string
value = entry.Value;
// Do something here
}
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
}
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:
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 MethodsAfter 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:
From the performance analysis, there is no doubt that performance of this way of ite
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.