[C#性能简析]泛型集合的使用

泛型实现了一种类型安全的算法重用,其最直接的应用正是在集合类中的性能与安全的良好体现,因此建议以泛型集合来代替非泛型集合。

下面以 List<T> 来说明,针对不同的数据类型(class,string,int)使用非泛型集合与使用泛型集合的程序性能差别。

(由于非泛型集合支持的参数类型为object,因此为了保证可比性,本文以List<object> 来代替非泛型集合。)

 

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Diagnostics;

namespace Test_Console
{
    class Program10
    {
        static void Main(string[] args)
        {
            Perf perf;

            testClass tc = new testClass(5);
            perf = new Perf();
            perf.PerfCompare<testClass>(tc);
            perf = null;

            string str = "newStr";
            perf = new Perf();
            perf.PerfCompare<string>(str);
            perf = null;

            int i = 2010;
            perf = new Perf();
            perf.PerfCompare<int>(i);
            perf = null;
        }
    }

    class Perf34
    {
        public void PerfCompare<T>(T testObj)
        {
            List<object> listObject = new List<object>();
            List<T> listT = new List<T>();

            long ms = 0;
            Stopwatch sw = new Stopwatch();
            sw.Start();

            for (int i = 0; i < 1000000; i++)
            {
                listObject.Add(testObj);
            }

            sw.Stop();
            ms = sw.ElapsedMilliseconds;
            sw.Reset();
            sw.Start();

            for (int i = 0; i < 1000000; i++)
            {
                listT.Add(testObj);
            }

            sw.Stop();

            Console.WriteLine("Compare Between [{0}] And [{1}]:", "object", testObj.GetType());
            Console.WriteLine(ms + " : " + sw.ElapsedMilliseconds);
            Console.WriteLine();
        }
    }


    class testClass
    {
        int testInt;

        public testClass(int i)
        {
            testInt = i;
        }
    }
}

 

 

运行结果如下:

 

由于testClass和string类型均为引用类型,因此,使用非泛型集合不需经过装箱过程,程序执行差别不大;

而对于int类型,若使用非泛型集合则需要经过装箱拆箱过程,故使用泛行集合会大大提高运行效率。

原文地址:https://www.cnblogs.com/cnliu/p/1672206.html