您的位置:首页 > 其它

List<T> 与ArrayList 性能比较

2013-02-18 11:35 519 查看
 ValueType 情况下:这二者性能相差显著,List<T> 要好太多,且没有装箱操作,也就没有GC回收次数太多的问题。

ReferenceType:性能相差不多。不过也是前者比后者好。

class ListTest
{
public static void EfficiencyTest()
{
ValueTypePerfTest();
ReferenceTypePerfTest();
}

private static void ValueTypePerfTest()
{
const int count = 10000000;
using (new OperationTimer("List<Int32>"))
{
List<Int32> l = new List<int>(count);
for (Int32 n = 0; n < count; n++)
{
l.Add(n);
Int32 x = l
;
}
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
;
}
a = null;
}
}

private static void ReferenceTypePerfTest()
{
const int count = 10000000;
using (new OperationTimer("List<String>"))
{
List<String> l = new List<String>(count);
for (Int32 n = 0; n < count; n++)
{
l.Add("X");
String x = l
;
}
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
;
}
a = null;
}
}
}

internal sealed class OperationTimer : IDisposable
{
private Int64 m_startTime;
private string m_Text;
private int m_collectionCount;

public OperationTimer(string text)
{
PrepareForOperation();
m_Text = text;
m_collectionCount = GC.CollectionCount(0);
m_startTime = Stopwatch.GetTimestamp();
}

public void Dispose()
{
Console.WriteLine("{0, 6:###.00} Seconds (GCs = {1, 3}) {2}", (Stopwatch.GetTimestamp() - m_startTime) / (double)Stopwatch.Frequency, GC.CollectionCount(0) - m_collectionCount, m_Text);
}

private static void PrepareForOperation()
{
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  arraylist ListT