using System; namespace FinalizeBenchmark { class Benchmark { /// /// Start with an arg to perform the Dispose benchmark. Start with no args for a no dispose benchmark. /// static void Main(string[] args) { // Get everything jitted DateTime x = DateTime.Now; FinalizeObject o = new FinalizeObject(); o.DoSomeWork(); o.Dispose(); o = new FinalizeObject(); // Collect and wait GC.Collect(); GC.WaitForPendingFinalizers(); // Benchmark if (args.Length != 0) { performBenchmarkDispose(); } else { performBenchmarkNoDispose(); } } static void performBenchmarkNoDispose() { DateTime start, end; start = DateTime.Now; for (int i = 0; i < 10000000; i++) { FinalizeObject o = new FinalizeObject(); o.DoSomeWork(); } GC.Collect(); GC.WaitForPendingFinalizers(); end = DateTime.Now; Console.WriteLine("No dispose time: {0}", end - start); } static void performBenchmarkDispose() { DateTime start, end; start = DateTime.Now; for (int i = 0; i < 10000000; i++) { FinalizeObject o = new FinalizeObject(); o.DoSomeWork(); o.Dispose(); } GC.Collect(); GC.WaitForPendingFinalizers(); end = DateTime.Now; Console.WriteLine("Dispose time: {0}", end - start); } } class FinalizeObject : IDisposable { private volatile int someInt; private static Random random = new Random(); public void DoSomeWork() { this.someInt = random.Next(10000000); } private bool disposed = false; public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected void Dispose(bool disposing) { if (disposed) return; disposed = true; if (disposing) { // Dispose Managed resources // Not needed in this class, but we could have a reference to // a managed object that has an unmanaged resource } // Unmanaged resources // Here we would get rid of direct unmanaged resources } ~FinalizeObject() { Dispose(false); } } }