紧跟上一章,废话不来,看下面.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Data;
using System.Data.SqlClient;
using System.Collections;
namespace DBTest
{
/// <summary>
/// 本次针对Dictionary与hashtable之间的
/// </summary>
class Program
{
private static DataTable table;
static void Main(string[] args)
{
GetTable();
Start();
Console.Read();
}
static void GetTable()
{
Stopwatch sw = new Stopwatch();
sw.Start();
string connstr = "Data Source=localhost;Initial Catalog=BigTable;Persist Security Info=True;User ID=***;Password=***";
SqlConnection conn = new SqlConnection(connstr);
SqlCommand command = new SqlCommand("select top 100000 * ,0 as dealed from urldata ",conn);
SqlDataAdapter sda = new SqlDataAdapter(command);
DataSet ds = new DataSet();
sda.Fill(ds);
table = ds.Tables[0];
sw.Stop();
Console.WriteLine("加载数据:{0}",sw.ElapsedMilliseconds);
}
static void Start()
{
Stopwatch sw = new Stopwatch();
sw.Start();
DicTest();
sw.Stop();
Console.WriteLine("Dictionary:{0}", sw.ElapsedMilliseconds);
sw.Reset();
sw.Start();
HashTest();
sw.Stop();
Console.WriteLine("Hashtable:{0}", sw.ElapsedMilliseconds);
}
static void DicTest()
{
Dictionary<string, int> dic = new Dictionary<string, int>();
string urlpath = null;
foreach (DataRow row in table.Rows)
{
urlpath = row["UrlPath"].ToString();
if (dic.ContainsKey(urlpath))
dic[urlpath]++;
else
dic.Add(urlpath, 1);
}
}
static void HashTest()
{
Hashtable ht = new Hashtable();
string urlpath;
foreach (DataRow row in table.Rows)
{
urlpath = row["UrlPath"].ToString();
if (ht.ContainsKey(urlpath)) //这里的装箱拆箱会产生影响.
ht[urlpath] = int.Parse(ht[urlpath].ToString());
else
ht.Add(urlpath, 1);
}
}
}
}
结果很明显,Dictionay要快那么一点点.但比起上一文章的速度快几十倍了.
最后,在此求指导,求有理的喷!