【发布时间】:2015-02-05 12:36:32
【问题描述】:
我有以下代码:
namespace ConsoleCodeGenerator
{
internal class Foo
{
public double F { get; set; }
}
internal class Program
{
private static void Main(string[] args)
{
//int size = 100000;
int size = 70000000;
List<Foo> list = new List<Foo>(size);
ArrayList arrayList = new ArrayList(size);
Stopwatch sw = new Stopwatch();
sw.Start();
for (int i = 0; i < size; i++)
{
Foo f = new Foo();
f.F = i;
list.Add(f);
}
sw.Stop();
Console.WriteLine("List: {0}", sw.ElapsedMilliseconds);
Stopwatch sw2 = new Stopwatch();
sw2.Start();
for (int i = 0; i < size; i++)
{
Foo f = new Foo();
f.F = i;
arrayList.Add(f);
}
sw2.Stop();
Console.WriteLine("arrayList: {0}", sw2.ElapsedMilliseconds);
}
}
}
如果我使用 int size = 100000;然后 List 以 2:6 毫秒的比例优于 ArrayList。但是如果要使 size = 70000000;然后 ArrayList 在我的计算机上具有更好的性能 5450:4809。看起来处理巨大的(大约数百万个项目)ArrayList 可能比 List 更快。为什么装箱/拆箱在小内存分配中很重要,而在大数组中无关紧要
【问题讨论】:
-
你的问题是......?
-
另外,请注意没有装箱/拆箱,因为您没有存储值类型。
-
List<>在后台使用ArrayList,因此性能应该几乎相同。List<>应该有一些额外的指令需要解释,但肉眼看不到 -
不,它没有使用 ArrayList,它使用了一个数组。检查我之前提到的参考来源。顺便说一句,ArrayList 也一样,它也使用了一个数组。
-
@Areius 我的源参考显示数组列表
protected ArrayList InnerList { get { if (list == null) list = new ArrayList(); return list; } }