Why dictionary is faster than HashTable
Consider this code:
[TestClass]
public class MyTestClass
{
private TestContext testContextInstance;
public TestContext TestContext
{
get { return testContextInstance; }
set { testContextInstance = value; }
}
[TestMethod]
[DeploymentItem("SampleData.xml")]
[DataSource("Microsoft.VisualStudio.TestTools.DataSource.XML",
"|DataDirectory|\\SampleData.xml",
"Row", DataAccessMethod.Sequential)]
public void MyTestMethod1()
{
int value = Convert.ToInt32(testContextInstance.DataRow["Data"]);
Stopwatch watch = new Stopwatch();
// Testing Dictionary for Reading and writing.
watch.Restart();
var dictionary = LoadDataTestForDictionary(value);
watch.Stop();
System.Diagnostics.Trace.WriteLine("Elapsed Milliseconds(Load
Dictionary): " +
watch.ElapsedMilliseconds.ToString());
watch.Restart();
ReadEachElementOfDictionary(dictionary);
watch.Stop();
System.Diagnostics.Trace.WriteLine("Elapsed Milliseconds(Read
Dictionary): " +
watch.ElapsedMilliseconds.ToString());
// Testing HashTable for Reading and writing.
watch.Restart();
var hash = LoadDataTestForHashTable(value);
watch.Stop();
System.Diagnostics.Trace.WriteLine("Elapsed Milliseconds(Load
HashTable): " +
watch.ElapsedMilliseconds.ToString());
watch.Restart();
ReadEachElementOfHashTable(hash);
watch.Stop();
System.Diagnostics.Trace.WriteLine("Elapsed Milliseconds(Read
HashTable): " +
watch.ElapsedMilliseconds.ToString());
}
public Dictionary<int, string> LoadDataTestForDictionary(int
totalRecords)
{
// Create Dictionary object.
Dictionary<int, string> dict = new Dictionary<int, string>();
for (int i = 0; i < totalRecords; i++)
{
dict.Add(i, "this is test data");
}
return dict;
}
public void ReadEachElementOfDictionary(Dictionary<int, string> dict)
{
for (int i = 0; i < dict.Count; i++)
{
var value = dict[i];
}
}
public Hashtable LoadDataTestForHashTable(int totalRecords)
{
Hashtable hTable = new Hashtable();
for (int i = 0; i < totalRecords; i++)
{
hTable.Add(i, "this is test data");
}
return hTable;
}
public void ReadEachElementOfHashTable(Hashtable htable)
{
for (Int64 i = 0; i < htable.Count; i++)
{
var value = htable[i];
}
}
}
This is my result:
We can seet taht dictonary is so faster than HashTable.Why? Source
No comments:
Post a Comment