相关疑难解决方法(0)

阵列与列表的性能

假设您需要有一个需要经常迭代的整数列表/数组,我的意思是非常频繁.原因可能有所不同,但它说它是高容量处理的最内循环的核心.

通常,由于其大小的灵活性,人们会选择使用列表(列表).最重要的是,msdn文档声称列表在内部使用数组,并且应该执行速度快(使用Reflector快速查看确认这一点).不用说,有一些开销.

有没有人真正测量过这个?通过列表迭代6M次与阵列相同的时间?

.net arrays generics performance list

181
推荐指数
5
解决办法
15万
查看次数

为什么 .NET 中的数组比列表快得多?

考虑以下代码:

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

namespace ListAllocationPerformance
{
    class Program
    {
        const int count = 100000000;

        public static object Memory { get; private set; }

        static void Main(string[] args)
        {
            Console.WriteLine(string.Format("count: {0}", count));
            MeasureFunction(FillListWithoutAllocation, "without allocation");
            MeasureFunction(FillListWithAllocation, "with allocation");
            MeasureFunction(FillArray, "array");
            MeasureFunction(FillUnmanagedArray, "unsafe array");
            string input = Console.ReadLine();
        }

        static void MeasureFunction(Action function, string name)
        {
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            function();
            stopwatch.Stop();
            Console.WriteLine(string.Format("Function {0} finished after \t {1}ms", name, stopwatch.ElapsedMilliseconds, count));
        }

        static void FillListWithoutAllocation()
        { …
Run Code Online (Sandbox Code Playgroud)

c# arrays performance list capacity

7
推荐指数
0
解决办法
9837
查看次数

标签 统计

arrays ×2

list ×2

performance ×2

.net ×1

c# ×1

capacity ×1

generics ×1