2010年7月12日 星期一

[.NET] ArrayList,Hashtable,Dictionary compare

Introduction
Sometime we need to save some const infotmation in Collection(ArrayList/HashTable in .NET Framework), and get some information from an indepentdent id.
Suppose you do not understand the data structure, maybe you will using array or arraylist to save const, then coding search algorithm by yourself.
If your const is excessive, maybe the program performance will be reduce.

Background
In my job, I have a event log manager, a event resource file and a event id definition.
I will load resource file used by event log manager, and the event will be save into an ArrayList object in memory.
Then I will add an event log by event id, the event log manager will return a event log where search from ArrayList everytime.
But in my program, add an event log is a repetitive behavior, so I think that maybe I can use a more efficient solution to improve it.


Comparation



I will use ArrayLit/HashTable/Dictionary to compare the search algorithm's performance.

I will test it on Windows XP and Windows CE 5.0 Emulator.
I have 2048 event log and these are non-continuous data.
private void btnArrayList_Click(object sender, EventArgs e)
{
int t_ulStartTime = AccurateTimer.GetTimeTick();
for (int i = 1000; i < 42880; i++)
{
m_event.AddEventLogWithArrayList(i);
}
int t_ulEndTime = AccurateTimer.GetTimeTick();
double t_r8PassedTime = (double)(t_ulEndTime - t_ulStartTime) / (double)1000.0;
MessageBox.Show("ArrayList spend time:" + t_r8PassedTime);
}

private void btnHashTable_Click(object sender, EventArgs e)
{
int t_ulStartTime = AccurateTimer.GetTimeTick();
for (int i = 1000; i < 42880; i++)
{
m_event.AddEventLogWithHashtable(i);
}
int t_ulEndTime = AccurateTimer.GetTimeTick();
double t_r8PassedTime = (double)(t_ulEndTime - t_ulStartTime) / (double)1000.0;
MessageBox.Show("Hashtable spend time:" + t_r8PassedTime);
}

private void btnDictionary_Click(object sender, EventArgs e)
{
int t_ulStartTime = AccurateTimer.GetTimeTick();
for (int i = 1000; i < 42880; i++)
{
m_event.AddEventLogWithDictionary(i);
}
int t_ulEndTime = AccurateTimer.GetTimeTick();
double t_r8PassedTime = (double)(t_ulEndTime - t_ulStartTime) / (double)1000.0;
MessageBox.Show("Dictionary spend time:" + t_r8PassedTime);
}




In my test, I found Hashtable's performance is best.
And I found the Hashtable is better then Dictionary.
If key is not exist in Dictionary, it will throw a System.Collections.Generic.KeyNotFoundException.
It will reduce the program's performance, and the generic in C# without a good performance, so I don't use it.

Reference

An Extensive Examination of Data Structures Using C# 2.0
Sample Code:Test Hashtable and ArrayList

沒有留言:

張貼留言

Hello