Wednesday, April 25, 2012

Object or Application memory footprint calculation – example


We many time encounter queries from management and architecture team about memory footprint of application. This is vital information which decides success of any implementation and innovation. Following is an example to find memory footprint of a class object created.

Main idea is basically finding system memory usage difference before and after creation of the object. This will not going to give you precise footprint but you can take 5 reading and take an average of it.
  • Namespace:  System
    • GC.GetTotalMemory Method - Retrieves the number of bytes currently thought to be allocated. A parameter indicates whether this method can wait a short interval before returning, to allow the system to collect garbage and finalize objects.
    • GC.WaitForFullGCComplete Method - Returns the status of a registered notification for determining whether a full garbage collection by the common language run time has completed.
    • GC.Collect Method - Forces an immediate garbage collection of all generations.


Sample code:
System.GC.Collect();
if (System.GC.WaitForFullGCComplete() == GCNotificationStatus.Succeeded)
{
    long GC_MemoryStart = System.GC.GetTotalMemory(true);
    // Create object or initialize application
    System.GC.Collect();
    if (System.GC.WaitForFullGCComplete() == GCNotificationStatus.Succeeded)
    {
        long GC_MemoryEnd = System.GC.GetTotalMemory(true);
        MessageBox.Show((GC_MemoryEnd - GC_MemoryStart).ToString()); // in bytes
    }
}

No comments:

Post a Comment