using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
private const int NumberInsertedKeys = 5000;
public static Hashtable hTable = new Hashtable();
public static Dictionary<int, string> dict = new Dictionary<int, string>();
public static decimal MemoryUsed;
public static decimal DictionaryMemoryUsed;
public static decimal HashtableMemoryUsed;
public static Stopwatch watch = new Stopwatch();
public static void Main()
Console.WriteLine("Dictionary VS Hashtable");
MemoryUsed = System.GC.GetTotalMemory(true) / 1024;
Msg("Started with this: {0:N0} KB", MemoryUsed);
private static void CollectMemory()
Console.WriteLine("\nMemory used after full collection: {0:N0}", GC.GetTotalMemory(true) / 1024);
private static void DictionaryTest()
Msg("\n--------- Results for {0}", "Dictionary");
InsertDataForDictionary();
Msg("Insert time taken (minutes): {0} or about {1} minutes and {2} seconds and milliseconds {3}", watch.Elapsed.TotalMinutes, watch.Elapsed.Minutes, watch.Elapsed.Seconds, watch.Elapsed.Milliseconds);
DictionaryMemoryUsed = (System.GC.GetTotalMemory(true) / 1024) - MemoryUsed - HashtableMemoryUsed;
Msg("MemoryUsed: {0:N0} KB", DictionaryMemoryUsed);
watch = Stopwatch.StartNew();
ReadEachElementOfDictionary();
Msg("Read time taken (minutes): {0} or about {1} minutes and {2} seconds and milliseconds {3}", watch.Elapsed.TotalMinutes, watch.Elapsed.Minutes, watch.Elapsed.Seconds, watch.Elapsed.Milliseconds);
private static void HashtableTest()
Msg("\n--------- Results for {0}", "Hashtable");
watch = Stopwatch.StartNew();
InsertDataForHashTable();
Msg("Insert time taken (minutes): {0} or about {1} minutes and {2} seconds and milliseconds {3}", watch.Elapsed.TotalMinutes, watch.Elapsed.Minutes, watch.Elapsed.Seconds, watch.Elapsed.Milliseconds);
HashtableMemoryUsed = (System.GC.GetTotalMemory(true) / 1024) - MemoryUsed - DictionaryMemoryUsed;
Msg("MemoryUsed: {0:N0} KB", HashtableMemoryUsed);
watch = Stopwatch.StartNew();
ReadEachElementOfHashTable();
Msg("Read time taken (minutes): {0} or about {1} minutes and {2} seconds and milliseconds {3}", watch.Elapsed.TotalMinutes, watch.Elapsed.Minutes, watch.Elapsed.Seconds, watch.Elapsed.Milliseconds);
private static void Msg(string name, params object[] args)
Console.WriteLine(name, args);
private static Dictionary<int, string> InsertDataForDictionary()
for (int i = 0; i < NumberInsertedKeys; i++)
dict.Add(i, "Test data " + i);
private static void ReadEachElementOfDictionary()
for (int i = 0; i < dict.Count; i++)
private static Hashtable InsertDataForHashTable()
for (int i = 0; i < NumberInsertedKeys; i++)
hTable.Add(i, "Test data " + i);
private static void ReadEachElementOfHashTable()
for (Int64 i = 0; i < hTable.Count; i++)