110,534
社区成员
发帖
与我相关
我的任务
分享
using System.Runtime.InteropServices;
using System.Diagnostics;
#region 优化
Stopwatch timer = new Stopwatch();
// initialize your code here
GC.Collect(2);
GC.WaitForPendingFinalizers();
GC.Collect(2);
GC.WaitForPendingFinalizers();
timer.Start();
//Do your test here
timer.Stop();
Console.WriteLine(timer.ElapsedMilliseconds.ToString());
#endregion
/*
在测试之前强制垃圾回收。WaitForPendingFinalizers()将会挂起当前线程,
直到GC完全结束。注意,这里强制进行了2次垃圾回收。
如果你对垃圾回收有所了解的话,那么应该知道当GC发现一个对象有Finalize()方法时,
会先调用Finalize(),然后到下一次GC发生时才回收这个对象,
我们确保在测试之前所有垃圾都已经回收释放了。
*/