Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
C# Finalizers performance test
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace Finalizers
{
internal class MyClass : IDisposable
{
public void Dispose()
{
// Should be uncomented to test case 'b'
//GC.SuppressFinalize(this);
}
// Should be uncomented to test Cases 'b' & 'c'
//~MyClass()
//{
//}
}
internal class Program
{
private static List<MyClass> _objs = new List<MyClass>(1*1000*1000);
private static void Main(string[] args)
{
var sw = Stopwatch.StartNew();
for (var i = 0; i < 10*1000*1000; i++)
{
using (var obj = new MyClass())
{
if (i % 1 == 0) // Replace with == 1 to stop storing objects
{
_objs.Add(obj);
}
}
}
_objs = null;
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds + " ms");
Console.WriteLine(GC.CollectionCount(2) + "/" + GC.CollectionCount(1) + "/" + GC.CollectionCount(0));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment