日期:2014-05-18 浏览次数:20724 次
using System; using System.Collections.Generic; using System.Diagnostics; using System.Collections; namespace GenericsTest { sealed class Program { static void Main(string[] args) { ValueTypePerfTest(); ReferenceTypePerfTest(); Console.ReadKey(); } 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[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 int count = 10000000; using (new OperationTimer("List<String>")) { List<string> l = new List<string>(); for (Int32 i = 0; i < count; i++) { l.Add("X"); String x = (String)l[i]; } l = null; } using (new OperationTimer("ArrayList Of String")) { ArrayList a = new ArrayList(); for (Int32 i = 0; i < count; i++) { a.Add("X"); String x = (String)a[i]; } a = null; } } } internal sealed class OperationTimer : IDisposable { public void Dispose() { Console.WriteLine("{0:###0.00000000} 秒, (GCS={1}) {2}", (Stopwatch.GetTimestamp() - m_startTime) / (double)Stopwatch.Frequency, GC.CollectionCount(0) - m_collectionCount, m_text); } private Int64 m_startTime; private String m_text; private Int32 m_collectionCount; public OperationTimer(String text) { PrepareForOperation(); m_text = text; m_collectionCount = GC.CollectionCount(0); m_startTime = Stopwatch.GetTimestamp(); } private static void PrepareForOperation() { GC.Collect(); 【 GC.WaitForPendingFinalizers(); GC.Collect();】 } } }
GC.WaitForPendingFinalizers();