Skip to content

Instantly share code, notes, and snippets.

@mattwarren
Created December 13, 2016 16:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattwarren/fea270125ae2d69a905e561f60bc470c to your computer and use it in GitHub Desktop.
Save mattwarren/fea270125ae2d69a905e561f60bc470c to your computer and use it in GitHub Desktop.
public static void TestMonitoringTotalAllocatedMemorySize()
{
AppDomain.MonitoringIsEnabled = true;
// provoke JIT, static ctors etc (was allocating 1740 bytes with first call)
var list = new List<string> { "stringA", "stringB" };
list.Sort();
var temp = new HashSet<string>();
var currentDomain = AppDomain.CurrentDomain;
GC.Collect();
var hashSetBefore = currentDomain.MonitoringTotalAllocatedMemorySize;
var countersToUse = new [] {1, 5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000, 100000, 250000, 500000};
foreach (var counter in countersToUse)
{
var loopCounter = 0;
for (int i = 0; i < counter; i++)
{
var test = new HashSet<string>();
loopCounter += test.Count;
}
Thread.Sleep(10);
GC.Collect();
var hashSetAfter = currentDomain.MonitoringTotalAllocatedMemorySize;
var totalAlloc = hashSetAfter - hashSetBefore;
Console.WriteLine(
"HashSet<string>() = {0,8:N2} bytes (Total = {1,12:N0} bytes, Counter = {2,8:N0}), Current = {3,8:N0} bytes",
(double)totalAlloc / counter, totalAlloc, counter, GC.GetTotalMemory(forceFullCollection: true));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment