类型List中采用泛型T的方式加入内容
而ArrayList中采用object的方式加入内容
using System;
using System.Collections.Generic;
using System.Collections;
using System.Diagnostics;
namespace ListDemo
{
class Program
{
static void Main(string[] args)
{
ValueTypePerfTest();
ReferenceTypePerfTest();
Console.ReadKey();
}
private static void ValueTypePerfTest()
{
const Int32 count = 100000000;
using (new OperationTimer("List<Int32>"))
{
List<Int32> l = new List<int>();
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 Int32 count = 100000000;
using (new OperationTimer("List<String>"))
{
List<string> l = new List<string>();
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 Stopwatch m_stopwatch;
private string m_text;
private Int32 m_collectionCount;
public OperationTimer(string text)
{
PrepareForOperation();
m_text = text;
m_collectionCount = GC.CollectionCount(0);
m_stopwatch = Stopwatch.StartNew();
}
public void Dispose()
{
Console.WriteLine("{0} (GCs={1,3})",
(m_stopwatch.Elapsed),
GC.CollectionCount(0) - m_collectionCount,
m_text);
}
private static void PrepareForOperation()
{
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}
}
}
运行结果:
分析:
ValueTypePerfTest中采用数值类型进行性能比较,list比arraylist要快得多。此外arraylist将对int32进行大量的装箱操作,最终需389次的垃圾回收
ReferenceTypePerfTest中采用引用类型进行性能比较,没有太多的差异。
1万+




被折叠的 条评论
为什么被折叠?



