程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> 關於.NET >> .NET 2.0中Hashtable快速查找的方法

.NET 2.0中Hashtable快速查找的方法

編輯:關於.NET

一般來說我們都是用 Hashtable 的 ContainsKey 方法來查找 Hashtable 中是否存在某個鍵值然後讀取他,但是這個方法並不是效率最好的方法。比較好的方法是直接讀取鍵值然後判斷這個對象是否為 null 然後讀取。兩種代碼分別如下:

  1. 一般慢速的方法:if (objHash.ContainsKey(keyValue)) 

        strValue=(String)objHash[keyValue]; 
    }
  2. 而快速的方法是:Object objValue=objHash[keyValue]; 
    if (objValue!=null) 

        strValue=(String)objValue; 
    }

兩種方法的速度經過測試能差一倍左右。下面是測試代碼:
Hashtable objHash = new Hashtable();
for (Int32 intI = 0; intI < 1000; intI++)
{
    objHash.Add("Key_" + intI.ToString(), "Value_" + intI.ToString());
}
String strValue = String.Empty;
Stopwatch timer = new Stopwatch();
timer.Start();
for (Int32 intI = 0; intI < 1000; intI++)
{
    Object objValue = objHash["Key_" + intI.ToString()];
    if (objValue != null)
    {
        strValue = (String)objValue;
    }
}
timer.Stop();
Console.WriteLine("Execution time was {0:F1} microseconds.", timer.Elapsed.Ticks / 10m);
timer.Reset();
timer.Start();
for (Int32 intI = 0; intI < 1000; intI++)
{
    if (objHash.ContainsKey("Key_" + intI.ToString()))
    {
        strValue = (String)objHash["Key_" + intI.ToString()];
    }
}
timer.Stop();
Console.WriteLine("Execution time was {0:F1} microseconds.", timer.Elapsed.Ticks / 10m);
timer.Reset();

測試結果如下:

如果不需要獲得對應鍵的值,而是只判斷的話,兩種方法的區別不會很明顯,大家有空可以測試下。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved