List<T> 与ArrayList 性能比较

 ValueType 情况下:这二者性能相差显著,List<T> 要好太多,且没有装箱操作,也就没有GC回收次数太多的问题。

ReferenceType:性能相差不多。不过也是前者比后者好。

    class ListTest
    {
        public static void EfficiencyTest()
        {
            ValueTypePerfTest();
            ReferenceTypePerfTest();
        }

        private static void ValueTypePerfTest()
        {
            const int count = 10000000;
            using (new OperationTimer("List<Int32>"))
            {
                List<Int32> l = new List<int>(count);
                for (Int32 n = 0; n < count; n++)
                {
                    l.Add(n);
                    Int32 x = l[n];
                }
                l = null;
            }

            using (new OperationTimer("ArrayList of Int32"))
            {
                ArrayList a = new ArrayList();
                for (Int32 n = 0; n < count; n++)
                {
                    a.Add(n);
                    Int32 x = (Int32)a[n];
                }
                a = null;
            }
        }

        private static void ReferenceTypePerfTest()
        {
            const int count = 10000000;
            using (new OperationTimer("List<String>"))
            {
                List<String> l = new List<String>(count);
                for (Int32 n = 0; n < count; n++)
                {
                    l.Add("X");
                    String x = l[n];
                }
                l = null;
            }

            using (new OperationTimer("ArrayList of String"))
            {
                ArrayList a = new ArrayList();
                for (Int32 n = 0; n < count; n++)
                {
                    a.Add("X");
                    String x = (String)a[n];
                }
                a = null;
            }
        }
    }

    internal sealed class OperationTimer : IDisposable
    {
        private Int64 m_startTime;
        private string m_Text;
        private int m_collectionCount;

        public OperationTimer(string text)
        {
            PrepareForOperation();
            m_Text = text;
            m_collectionCount = GC.CollectionCount(0);
            m_startTime = Stopwatch.GetTimestamp();
        }

        public void Dispose()
        {
            Console.WriteLine("{0, 6:###.00} Seconds (GCs = {1, 3}) {2}", (Stopwatch.GetTimestamp() - m_startTime) / (double)Stopwatch.Frequency, GC.CollectionCount(0) - m_collectionCount, m_Text);
        }

        private static void PrepareForOperation()
        {
            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();
        }
    }

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值