C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Note: This is a benchmark for testing the performance of looking up a key that was added first, and another key that was added last.
And: A reference is retained to the first and last keys added. This involves two string variables.
Result: The two tight loops then show the performance difference between looking up entries in the Dictionary that were added first, and last.
C# program that tests Dictionary performance and order
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
class Program
{
const int _max = 10000000;
static void Main()
{
double msA = 0, msB = 0;
//
// Ten tests of dictionary order.
//
for (int y = 0; y < 10; y++)
{
var dictionary = new Dictionary<string, int>(StringComparer.Ordinal);
string first = Path.GetRandomFileName();
dictionary.Add(first, 1);
for (int i = 0; i < 1000000; i++)
{
dictionary.Add(Path.GetRandomFileName(), 1);
}
string last = Path.GetRandomFileName();
dictionary.Add(last, 1);
//
// Test the dictionaries.
//
var s1 = Stopwatch.StartNew();
for (int i = 0; i < _max; i++)
{
int v;
dictionary.TryGetValue(first, out v);
}
s1.Stop();
var s2 = Stopwatch.StartNew();
for (int i = 0; i < _max; i++)
{
int v;
dictionary.TryGetValue(last, out v);
}
s2.Stop();
msA += s1.Elapsed.TotalMilliseconds;
msB += s2.Elapsed.TotalMilliseconds;
Console.Write(".");
//
// Collect the garbage.
//
GC.Collect();
}
Console.WriteLine();
Console.WriteLine(msA.ToString("0.00") + " ms");
Console.WriteLine(msB.ToString("0.00") + " ms");
Console.Read();
}
}
Output
(Second number is the last key search time elapsed.)
..........
3539.57 ms
3203.58 ms [Faster]
And: The program uses completely random path strings, so results will vary each pass through the loop.
Note: Each hash code is not unique. And each index is even less likely to be unique. Collisions are stored in a logical linked list.
Then: When you look up that key, the search algorithm loops through those entries in order, with the last key checked first.
Generally: The Dictionary lookup performance is good regardless of ordering if the hash code computation is well-distributed.
However: For certain in-memory database programs, adding keys in order of ascending hit frequency could improve performance.