Hashtable与Dictionary的区别

Hashtable Dictionary
乱序 顺序
键不唯一 键唯一
弱类型 强类型
会有装拆箱 没有装拆箱
效率低 效率高
线程安全 线程不安全

private void test()
{
    Stopwatch stopw = Stopwatch.StartNew();
    Random ran = new Random();

    stopw.Start();
    Dictionary<string, Student> dic = new Dictionary<string, Student>();
    for (int i = 0; i < 1000000; i++)
    {
        Student s = new Student();
        s.Name = "s" + i.ToString();
        s.Score = ran.Next(20, 151);
        dic.Add(s.Name, s);
    }
    stopw.Stop();
    long dicv = stopw.ElapsedMilliseconds;

    stopw.Reset();
    stopw.Start();
    Hashtable table = new Hashtable();
    for (int i = 0; i < 1000000; i++)
    {
        Student s = new Student();
        s.Name = "s" + i.ToString();
        s.Score = ran.Next(20, 151);
        table.Add(s.Name, s);
    }
    stopw.Stop();
    long tblv = stopw.ElapsedMilliseconds;

    MessageBox.Show(dicv.ToString() + "|" + tblv.ToString());
    //1605 1342 1412 1448 1287
    //2153 2501 2248 2186 2222
}

发表评论

电子邮件地址不会被公开。 必填项已用*标注