C# Hashtable VS. Dictionary 性能對比


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,在數量較小的時候,是沒啥問題的。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2026 CODEPRJ.COM