您的位置:首页 > 其它

为什么要使用泛型?泛型和非泛型对比

2016-10-20 23:08 302 查看
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 泛型和非泛型对比
{
class Program
{
static void Main(string[] args)
{
testGeneric();
testNonGeneric();
Console.ReadKey();
}
//测试泛型类型操作的运行时间
public static void testGeneric()
{
Stopwatch stopwatch = new Stopwatch();
List<int> list = new List<int>();
stopwatch.Start();
for (int i = 0; i < 10000000; i++)
{
list.Add(i);
}
stopwatch.Stop();
TimeSpan ts = stopwatch.Elapsed;
string elapsedTime = string.Format("{0:00}:{1:00}:{2:00}:{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.TotalMilliseconds / 10);
Console.WriteLine("泛型类型运行的时间:" + elapsedTime);
}
public static void testNonGeneric()
{
Stopwatch stopwatch = new Stopwatch();
ArrayList arraylist = new ArrayList();
stopwatch.Start();
for (int i = 0; i < 10000000; i++)
{
arraylist.Add(i);
}
stopwatch.Stop();
TimeSpan ts = stopwatch.Elapsed;
string elapsetime = string.Format("{0:00}:{1:00}:{2:00}:{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10);
Console.WriteLine("非泛型运行的时间:" + elapsetime);

}
}
}


运行效果图:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: