gpt4 book ai didi

.net - 数组与列表的性能

转载 作者:行者123 更新时间:2023-12-03 04:13:56 24 4
gpt4 key购买 nike

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

一般来说,人们会选择使用列表(List),因为它们的大小具有灵 active 。最重要的是,msdn 文档声称列表在内部使用数组,并且执行速度应该一样快(使用 Reflector 快速查看即可证实这一点)。尽管如此,还是会涉及一些开销。

有人实际测量过吗?迭代列表 6M 次与数组花费的时间相同吗?

最佳答案

非常容易测量...

在少量的紧密循环处理代码中我知道长度是固定的我使用数组来进行额外的微小优化;如果您使用索引器/作为表单,数组可以略微更快 - 但 IIRC 认为这取决于数组中数据的类型。但除非您需要进行微优化,否则请保持简单并使用 List<T>等等

当然,这仅适用于您正在读取所有数据的情况;对于基于键的查找,字典会更快。

这是我使用“int”的结果(第二个数字是校验和,以验证它们都做了相同的工作):

(已编辑以修复错误)

List/for: 1971ms (589725196)
Array/for: 1864ms (589725196)
List/foreach: 3054ms (589725196)
Array/foreach: 1860ms (589725196)

基于测试设备:

using System;
using System.Collections.Generic;
using System.Diagnostics;
static class Program
{
static void Main()
{
List<int> list = new List<int>(6000000);
Random rand = new Random(12345);
for (int i = 0; i < 6000000; i++)
{
list.Add(rand.Next(5000));
}
int[] arr = list.ToArray();

int chk = 0;
Stopwatch watch = Stopwatch.StartNew();
for (int rpt = 0; rpt < 100; rpt++)
{
int len = list.Count;
for (int i = 0; i < len; i++)
{
chk += list[i];
}
}
watch.Stop();
Console.WriteLine("List/for: {0}ms ({1})", watch.ElapsedMilliseconds, chk);

chk = 0;
watch = Stopwatch.StartNew();
for (int rpt = 0; rpt < 100; rpt++)
{
for (int i = 0; i < arr.Length; i++)
{
chk += arr[i];
}
}
watch.Stop();
Console.WriteLine("Array/for: {0}ms ({1})", watch.ElapsedMilliseconds, chk);

chk = 0;
watch = Stopwatch.StartNew();
for (int rpt = 0; rpt < 100; rpt++)
{
foreach (int i in list)
{
chk += i;
}
}
watch.Stop();
Console.WriteLine("List/foreach: {0}ms ({1})", watch.ElapsedMilliseconds, chk);

chk = 0;
watch = Stopwatch.StartNew();
for (int rpt = 0; rpt < 100; rpt++)
{
foreach (int i in arr)
{
chk += i;
}
}
watch.Stop();
Console.WriteLine("Array/foreach: {0}ms ({1})", watch.ElapsedMilliseconds, chk);

Console.ReadLine();
}
}

关于.net - 数组与列表的性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/454916/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com