质疑CLR Via C#中的一段代码,求指教狠批,只要能求得答案!!
这个问题困扰了大半个月了,睡觉之前老在琢磨!憋不住了来CSDN求解释!大恩不言谢!
代码是该书第三版 泛型部分P244
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();
class Program{ static void Main(string[] args) { int i = GetCharacterCount("a?bc?"); } static int GetCharacterCount(string str) { if (str == null) throw new ArgumentException("str"); //<-- return new System.Globalization.StringInfo(str).LengthInTextElements; }}
[解决办法]
知道个大概就差不多了对于clr没有多深入的严究。如果有那个时不如垃圾收集的原理,并不是.net的垃圾收集。