https://github.com/somdipdey/performance-difference-between-different-ways-of-iterating-over-a-dictionary-in-csharp
Performance Difference Between Different Ways Of Iterating Over A Dictionary in C#
https://github.com/somdipdey/performance-difference-between-different-ways-of-iterating-over-a-dictionary-in-csharp
csharp csharp-code dictionary dictionary-variable iterables iterator key-value
Last synced: 6 months ago
JSON representation
Performance Difference Between Different Ways Of Iterating Over A Dictionary in C#
- Host: GitHub
- URL: https://github.com/somdipdey/performance-difference-between-different-ways-of-iterating-over-a-dictionary-in-csharp
- Owner: somdipdey
- Created: 2017-11-10T14:08:45.000Z (almost 8 years ago)
- Default Branch: master
- Last Pushed: 2017-11-10T14:36:46.000Z (almost 8 years ago)
- Last Synced: 2025-02-15T10:31:22.186Z (8 months ago)
- Topics: csharp, csharp-code, dictionary, dictionary-variable, iterables, iterator, key-value
- Language: C#
- Size: 9.77 KB
- Stars: 0
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Performance-Difference-Between-Different-Ways-Of-Iterating-Over-A-Dictionary-In-CSharp (C#)
This program 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:C#
Dictionary profilingDictionary;## Method1
Using old-school for loop as follows:C#
for (int i = 0; i < profilingDictionary.Count; i++ )
{
int key = i;
string value = profilingDictionary[i];
// Do something here
}
## Method 2
Using foreach lazy coding as follows:C#
foreach (var entry in profilingDictionary)
{
int key = entry.Key;
string value = entry.Value;
// Do something here
}
## Method 3
Using foreach non-lazy coding (statically typed) as follows:C#
foreach (KeyValuePair 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 staticaly typed foreach iteration over a Dictionary variable is by far the best performing out of the three.