C# Hashtable VS. Dictionary 效能對比
阿新 • • 發佈:2020-11-20
Hashtable VS Dictionary
- 因為Hashtable的Key和Value都是object型別,所以在使用值型別的時候,必然會出現裝箱和拆箱的操作,因此效能肯定是不如Dictionary的,在此就不做過多比較了。
在此僅比較<string,string>的情況
`
class Program
{
static void Main(string[] args)
{
int nTimes = 10000; //排除定時器啟動誤差 Stopwatch sw_D = new Stopwatch(); sw_D.Restart(); for (int i = 0; i < 10; i++) { Thread.Sleep(100); } sw_D.Stop(); //Dictionary部分 Dictionary<string, string> dict = new Dictionary<string, string>(); sw_D.Restart(); for (int i = 0; i < nTimes; i++) { string str = i.ToString(); dict.Add(str, str); } sw_D.Stop(); decimal decTime_D = sw_D.ElapsedTicks / (decimal)Stopwatch.Frequency; Console.WriteLine(decTime_D); sw_D.Restart(); for (int i = 0; i < nTimes; i++) { string str = dict[i.ToString()]; } sw_D.Stop(); decTime_D = sw_D.ElapsedTicks / (decimal)Stopwatch.Frequency; Console.WriteLine(decTime_D); //Hashtable部分 Hashtable hashtable = new Hashtable(); Stopwatch sw_H = new Stopwatch(); sw_H.Restart(); for (int i = 0; i < nTimes; i++) { string str = i.ToString(); hashtable.Add(str, str); } sw_H.Stop(); decimal decTime_H = sw_H.ElapsedTicks / (decimal)Stopwatch.Frequency; Console.WriteLine(decTime_H); sw_H.Restart(); for (int i = 0; i < nTimes; i++) { object obj = hashtable[i.ToString()]; } sw_H.Stop(); decTime_H = sw_H.ElapsedTicks / (decimal)Stopwatch.Frequency; Console.WriteLine(decTime_H); Console.ReadKey(); } }
- 在10000的數量級
第一次計算Dictionary的誤差比較大,相差有1/2之多。
總體來看,Hashtable在查詢上比Dictionary要強
0.0016746
0.0021346
0.0015785
0.0011693
- 在100000的數量級
這一次,不管怎麼樣,Dictionary都要強於Hashtable,這就很奇怪了
0.0155579
0.0150943
0.0196156
0.0189904
而且很明顯的,Dictionary的時間要小於之前的上一個數量級中的10倍,也就是在資料量較大的時候對效能做了優化?
相反,Hashtable的時間顯然是要大於之前的10倍的,也就是佔用記憶體變大了很多之後,hashtable的效能降低了很多。
為了繼續驗證是不是在資料量較小的時候,是不是Hashtable效能更優,再測試一下100的數量級
- 在100的數量級
很明顯,Hashtable要遠強於Dictionary。
0.0001577
0.0000612
0.0000435
0.0000344
總結
在都是引用型別的情況下,數量級較小,可以將Dictionary改成Hashtable使用。數量級較大,建議選擇Dictionary。
至於為什麼在大數量級別下會出現“反轉”,這個還有待後面考量。
不過可以預見的是,在WPF中依賴屬性都存在於一張Hashtable,在數量較小的時候,是沒啥問題的。