高效代码指泛型代替非泛型

用泛型代替非泛型,提高效率。

今天测试了一下使用泛型和非泛型的效率问题,结果一目了然。

例子代码如下:

public class Test

{

static int collectionCount = 0;
static Stopwatch watch = null;
static int testCount = 1000000;

public static void TestBegin()
{
GC.Collect();////强制对所有代码进行垃圾回收
GC.WaitForPendingFinalizers();////挂起线程,直到处理终结器队列的线程清空改队列。
GC.Collect();////再此回收。
collectionCount = GC.CollectionCount(0);////返回在代码执行中垃圾回收次数
watch = new Stopwatch();
watch.Start();

}

public static void TestEnd()
{
watch.Stop();
Console.WriteLine("消耗的时间:{0}",watch.ElapsedMilliseconds.ToString());
Console.WriteLine("垃圾回收的次数:{0}",GC.CollectionCount(0)-collectionCount);
}

/// <summary>
/// 测试arraylist性能
/// </summary>
public static void TestArrayList()
{
ArrayList arrayList = new ArrayList();
int temp = 0;
for (int i = 0; i < testCount; i++)
{
arrayList.Add(i);
temp=(int)arrayList[i];
}
arrayList = null;
}

/// <summary>
/// 测试泛型的性能
/// </summary>
public static void TestGenericList()
{
List<int> list = new List<int>();
int temp = 0;
for (int i = 0; i < testCount;i++ )
{
list.Add(i);
temp=list[i];
}
list = null;
}

public static void main(string []args)

{

Console.WriteLine("开始测试性能arraylist");
TestBegin();
TestArrayList();
TestEnd();

Console.WriteLine("开始测试性能List<T>泛型:");
TestBegin();
TestGenericList();
TestEnd();

Console.ReadLine();

}

}

 

运行结果如下:

 

可以看到,泛型的效率高很多。

posted @ 2015-09-01 11:48  明&天  阅读(313)  评论(1编辑  收藏  举报