泛型與非泛型代碼效能比較
來源:互聯網
上載者:User
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
namespace ConsoleApplication1
{
//非泛型類
public class RegularStack
{
private object[] frames;
private int pointer = 0;
public RegularStack(int size)
{
this.frames = new object[size];
}
//進棧
public void Push(object frame)
{
this.frames[pointer++] = frame;
}
//出棧
public object Pop()
{
return this.frames[--pointer];
}
}
//泛型類
public class GenericStack<T>
{
private T[] frames;
private int pointer = 0;
public GenericStack(int size)
{
this.frames = new T[size];
}
//進棧
public void Push(T frame)
{
this.frames[pointer++] = frame;
}
//出棧
public object Pop()
{
return this.frames[--pointer];
}
}
public class Rectangle
{
public static void Main()
{
int iterations = 10000000; //迴圈次數
//RegularStack s = new RegularStack(iterations); //執行非泛型
GenericStack<int> s = new GenericStack<int>(iterations); //執行泛型
DateTime start = DateTime.Now; //開始時間
for (int i = 0; i < iterations; i++)
s.Push(i); //進棧
for (int i = 0; i < iterations; i++)
s.Pop(); //出棧
float ticks = DateTime.Now.Ticks - start.Ticks;
float duration = ticks / TimeSpan.TicksPerSecond; //花費時間
Console.WriteLine("Duration = " + string.Format("{0:#0.0000}", duration));
}
}
}
// int iterations = 100000; //迴圈次數
// 執行非泛型花費時間: 0.0156
// 執行泛型花費時間: 0.0000
// int iterations = 1000000; //迴圈次數
// 執行非泛型花費時間: 0.0938
// 執行泛型花費時間: 0.0313
// int iterations = 10000000; //迴圈次數
// 執行非泛型花費時間: 2.7183
// 執行泛型花費時間: 0.4063