C#泛型与非泛型性能比较的实例_技术学院_宜昌市隼壹珍商贸有限公司

您好,欢迎访问宜昌市隼壹珍商贸有限公司

400 890 5375
当前位置: 主页 > 新闻动态 > 技术学院

C#泛型与非泛型性能比较的实例

发布时间:2026-01-17  |  点击率:

复制代码 代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace ConsoleApplication
{
    class Program
    {
        static int length = 1000 * 1000;
        static void Main(string[] args)
        {
            int iteration=10;//方法执行次数
            CodeTimer.Time("值类型处理-泛型方法", iteration, Test1);
            CodeTimer.Time("值类型处理-非泛型方法", iteration, Test2);
            //CodeTimer.Time("引用类型处理-泛型方法", iteration, Test3);
            //CodeTimer.Time("引用类型处理-非泛型方法", iteration, Test4);
            Console.ReadKey();
        }
        /// <summary>
        /// 值类型泛型方法
        /// </summary>
        static  void Test1()
        {
            List<int> l = new List<int>();
            for (int i = 0; i < length; i++)
            {
                l.Add(i);
                int a = l[i];
            }
            l = null;
        }
        /// <summary>
        /// 值类型非泛型方法
        /// </summary>
        static void Test2()
        {
            ArrayList a = new ArrayList();
            for (int i = 0; i < length; i++)
            {
                a.Add(i);
                int s = (int)a[i];
            }
            a = null;
        }
        /// <summary>
        /// 引用类型泛型方法
        /// </summary>
        static void Test3()
        {
            List<string> l = new List<string>();
            for (int i = 0; i < length; i++)
            {
                l.Add("l");
                string s = l[i];
            }
        }
        /// <summary>
        /// 引用类型的非泛型方法
        /// </summary>
        static void Test4()
        {
            ArrayList a = new ArrayList();
            for(int i=0;i<length;i++)
            {
                a.Add("a");
                string s = (string)a[i];
            }
            a = null;
        }
    }
}

值类型的泛型与非泛型的性能比较,方法执行10次,由此可见 使用泛型要比非泛型的效率高很多。

全国统一服务电话

400 890 5375

电子邮箱:879577@qq.com

公司地址:宜昌市西陵区黄河路5号三峡明珠10栋1051室

咨询微信

TEL:13680874598