Home | Contact Us

CSharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript

C# Dictionary GetEnumerator

This C# article uses the GetEnumerator method on Dictionary. It provides a benchmark.

Dictionary GetEnumerator. The Dictionary type abstracts out its looping logic into enumerators.

These are accessed through the foreach-loop and the GetEnumerator method. We demonstrate the GetEnumerator method. It exhibits better performance than foreach.

Example. Let's examine the most common way to loop through a Dictionary instance. The foreach-loop here actually compiles into intermediate language that uses the GetEnumerator method, MoveNext, and Current—as well as a try-finally block.


Looping over Dictionary with foreach: C#

static int A(Dictionary<string, int> d)
    int a = 0;
    foreach (var pair in d)
	a += pair.Value;
    return a;

Example 2. Next, this method directly demonstrates the GetEnumerator and MoveNext methods and the Current property. This code is compiled to the same intermediate language except the try-finally block is absent.

Difference: Method B is harder to read and it also omits the try-finally construct that was added by the C# compiler.

Looping over Dictionary with GetEnumerator: C#

static int B(Dictionary<string, int> d)
    int b = 0;
    var enumerator = d.GetEnumerator();
    while (enumerator.MoveNext())
	var pair = enumerator.Current;
	b += pair.Value;
    return b;

Performance. I tested the two methods. The benchmark harness is available in the link below. The dictionary initialization code is shown below as well. And finally we see that method B was faster by a fairly constant amount.

Benchmark ProgramsVar Examples

Dictionary initialization: C#

var d = new Dictionary<string, int>();
d["one"] = 1;
d["two"] = 2;
d["three"] = 3;
d["four"] = 4;
d["five"] = 5;


Method A (foreach):       92.07 ns
Method B (GetEnumerator): 88.53 ns

Summary. Using GetEnumerator directly is somewhat faster than using the foreach-loop on Dictionary. The finally statement actually calls the enumerators Dispose method, which has an empty implementation.

Thus: GetEnumerator is worth considering as a way to improve Dictionary performance in certain C# programs.

GetEnumerator List Example