第一步 ,新建测试的接口和类 。
public interface ITest
{
void M();
}
public class Test1:ITest
{
public void M()
{
}
}
class Test
{
public Test()
{
}
}
第二步,分别比较 int,class,Interface在hashtable的速度
class Program
{
static void Main(string[] args)
{
int CompareCount = 100000;
Hashtable table1 = new Hashtable();
System.Diagnostics.Stopwatch stopWatch1 = new System.Diagnostics.Stopwatch();
stopWatch1.Start();
for (int i = 0; i < CompareCount; i++)
{
table1.Add(i, i);
}
stopWatch1.Stop();
for (int i = 0; i < CompareCount; i++)
{
int o = (int)table1[i];
}
string t2 = stopWatch1.ElapsedTicks.ToString();
Console.WriteLine("int:" + t2);
Hashtable table = new Hashtable();
System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
stopwatch.Start();
for (int i = 0; i < CompareCount; i++)
{
table.Add(i, new Test());
}
stopwatch.Stop();
for (int i = 0; i < CompareCount; i++)
{
Test o = table[i] as Test;
}
string t1 = stopwatch.ElapsedTicks.ToString();
Console.WriteLine("class:"+ t1);
Hashtable table2 = new Hashtable();
System.Diagnostics.Stopwatch stopWatch2 = new System.Diagnostics.Stopwatch();
stopWatch2.Start();
for (int i = 0; i < CompareCount; i++)
{
ITest test2 = new Test1();
table2.Add(i,test2);
}
stopWatch2.Stop();
for (int i = 0; i < CompareCount; i++)
{
ITest o = table2[i] as ITest;
}
string t3 = stopWatch2.ElapsedTicks.ToString();
Console.WriteLine("Interface:"+t3);
Console.Read();
}
}
比较结果如下:
CompareCount = 100000;
Debug=1
int:27037
class:38347
Interface:134340
Debug=2
int:27654
class:37086
Interface:134569
Run=1
int:29618
class:41159
Interface:152794
Run=2
int:27703
class:40221
Interface:155381