C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Tip: If looping through elements is a common task in a program, a List is more efficient.
Also: Some dummy code ensures that the loop executes and is not optimized out by the JIT compiler.
C# program that benchmarks loops
using System;
using System.Collections.Generic;
using System.Diagnostics;
class Program
{
static void Main()
{
var dictionary = new Dictionary<string, int>();
dictionary["a"] = 1;
dictionary["b"] = 2;
dictionary["c"] = 3;
dictionary["d"] = 4;
dictionary["e"] = 5;
var list = new List<string>();
list.Add("a");
list.Add("b");
list.Add("c");
list.Add("d");
list.Add("e");
var s1 = Stopwatch.StartNew();
const int max = 10000000;
for (int i = 0; i < max; i++)
{
Method1(dictionary);
}
s1.Stop();
var s2 = Stopwatch.StartNew();
for (int i = 0; i < max; i++)
{
Method2(list);
}
s2.Stop();
Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) /
max).ToString("0.00 ns"));
Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000000) /
max).ToString("0.00 ns"));
Console.Read();
}
static void Method1(Dictionary<string, int> collection)
{
foreach (var pair in collection)
{
if (pair.Key == "z")
throw new Exception();
}
}
static void Method2(List<string> collection)
{
foreach (var value in collection)
{
if (value == "z")
throw new Exception();
}
}
}
Output
117.18 ns
78.19 ns
However: If looping time is prominent, the List would provide better performance.