假设您需要有一个需要经常迭代的整数列表/数组,我的意思是非常频繁.原因可能有所不同,但它说它是高容量处理的最内循环的核心.
通常,由于其大小的灵活性,人们会选择使用列表(列表).最重要的是,msdn文档声称列表在内部使用数组,并且应该执行速度快(使用Reflector快速查看确认这一点).不用说,有一些开销.
有没有人真正测量过这个?通过列表迭代6M次与阵列相同的时间?
考虑以下代码:
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)