C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Then: We measure lookup times for the first half of words, such that all keys exist.
BenchmarkInfo: The List is trimmed to half its size with Take, and then the second Dictionary is created. We use the Take and ToDictionary methods from LINQ.
Take, TakeWhileToDictionaryAnd: Each call to ContainsKey succeeds and returns true. We have a 100% hit rate here.
C# program that benchmarks Dictionary instances
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
class Program
{
static void Main()
{
// Read in list of English words.
var lines = new List<string>(File.ReadAllLines("enable1.txt"));
// This dictionary contains all strings. [172820 keys]
var dictionary1 = lines.ToDictionary(s => s, s => true);
// Shrink the List to half its size.
lines = lines.Take(lines.Count / 2).ToList();
// This dictionary contains half. [86410 keys]
var dictionary2 = lines.ToDictionary(s => s, s => true);
const int m = 100;
Stopwatch s1 = Stopwatch.StartNew();
for (int i = 0; i < m; i++)
{
foreach (string s in lines)
{
if (!dictionary1.ContainsKey(s))
{
throw new Exception();
}
}
}
s1.Stop();
Stopwatch s2 = Stopwatch.StartNew();
for (int i = 0; i < m; i++)
{
foreach (string s in lines)
{
if (!dictionary2.ContainsKey(s))
{
throw new Exception();
}
}
}
s2.Stop();
Console.WriteLine("{0},{1}", s1.ElapsedMilliseconds, s2.ElapsedMilliseconds);
Console.Read();
}
}
Dictionary size and performance benchmark
Full Dictionary: 791 ms
Half-size Dictionary: 591 ms [faster]
Therefore: Reducing total hashtable size enhances average performance with fewer collisions.