zoukankan      html  css  js  c++  java
  • NET 2.0中Hashtable快速查找的方法

    一般来说我们都是用 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();

    测试结果如下:

    如果不需要获得对应键的值,而是只判断的话,两种方法的区别不会很明显,大家有空可以测试下。

  • 相关阅读:
    web通信浅析(上B/S交互)转载
    tomcat内部运行原理浅析转载
    oracle集合运算
    Oracle 游标使用全解
    oracle 一些基本概念
    1.搭建项目环境之TestDirector 8.0
    修改Win7远程桌面端口
    从第二份工作开始
    2.搭建项目环境之源代码管理SVN
    How to Get IIS Web Sites Information Programmatically
  • 原文地址:https://www.cnblogs.com/sail/p/2061936.html
Copyright © 2011-2022 走看看