解析Hashtable、Dictionary、SortedDictionary、SortedList的效率

 
  
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;

namespace DictionaryTest
{
class Program
{
private static int totalCount = 10000 ;

static void Main( string [] args)
{
HashtableTest();
DictionaryTest();
SortedDictionaryTest();
Console.ReadKey();
}

private static void HashtableTest()
{
Hashtable hastable
= new Hashtable();
Stopwatch watch
= new Stopwatch();
watch.Start();
for ( int i = 1 ; i < totalCount; i ++ )
{
hastable.Add(i,
0 );
}
watch.Stop();
Console.WriteLine(
string .Format( " Hashtable添加{0}个元素耗时:{1}ms " , totalCount, watch.ElapsedMilliseconds));
Console.WriteLine(
" Hashtable不做查找测试 " );
hastable.Clear();
}

private static void DictionaryTest()
{
Dictionary
< int , int > dictionary = new Dictionary < int , int > ();
Stopwatch watch
= new Stopwatch();
watch.Start();
for ( int i = 1 ; i < totalCount; i ++ )
{
dictionary.Add(i,
0 );
}
watch.Stop();
Console.WriteLine(
string .Format( " Dictionary添加{0}个元素耗时:{1}ms " , totalCount, watch.ElapsedMilliseconds));
watch.Reset();
watch.Start();
dictionary.Select(o
=> o.Key % 1000 == 0 ).ToList().ForEach(o => { });
watch.Stop();
Console.WriteLine(
string .Format( " Dictionary查找能被1000整除的元素耗时:{0}ms " , watch.ElapsedMilliseconds));
dictionary.Clear();
}

private static void SortedDictionaryTest()
{
SortedDictionary
< int , int > dictionary = new SortedDictionary < int , int > ();
Stopwatch watch
= new Stopwatch();
watch.Start();
for ( int i = 1 ; i < totalCount; i ++ )
{
dictionary.Add(i,
0 );
}
watch.Stop();
Console.WriteLine(
string .Format( " SortedDictionary添加{0}个元素耗时:{1}ms " , totalCount, watch.ElapsedMilliseconds));
watch.Reset();
watch.Start();
dictionary.Select(o
=> o.Key % 1000 == 0 ).ToList().ForEach(o => { });
watch.Stop();
Console.WriteLine(
string .Format( " SortedDictionary查找能被1000整除的元素耗时:{0}ms " , watch.ElapsedMilliseconds));
dictionary.Clear();
}
}
}
2011052411195766.jpg全文:http://www.cnblogs.com/moozi/archive/2010/05/23/1741980.html

转载于:https://www.cnblogs.com/shikyoh/archive/2011/05/24/2055196.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值