[C#效能簡析]-泛型集合的使用

來源:互聯網
上載者:User

泛型實現了一種型別安全的演算法重用,其最直接的應用正是在集合類中的效能與安全的良好體現,因此建議以泛型集合來代替非泛型集合。

下面以 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類型,若使用非泛型集合則需要經過裝箱拆箱過程,故使用泛行集合會大大提高運行效率。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.