首页 > 代码库 > 为什么要使用泛型?泛型和非泛型对比

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

 

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);

        }
    }
}

运行效果图:

技术分享

 

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