IntroductionThis is my first time doing this and I’m sure I’ll muck things up somewhere along the way. I don’t consider myself an expert on this subject. I simply have done enough investigation in this area to have some interesting insights on the subject.
Why should I care?After all one of the reasons you chose a managed environment is to forget about memory management. You pay a price for garbage collection. Bad algorithms cause the garbage collector to work harder. Simple program, Count the number of words in a document using string.Split() and then get the length of the array.
This program is spending about 20 to 50% of its time just trying to manage the memory. Paying attention to memory can give even a small program a 20 to 50% performance boost. More efficient alternatives later for now just understand it creates a lot of objects and throws them away. In this run there were 2 peaks that reached a little over 70%.
The stack is where local variables are allocated.The heap is where malloc and new allocate space.
As programs request memory the system allocates it from the heap.
As programs release memory open spots appear in the heap. Eventually this area becomes fragmented and the system has to search through a list of free space to find enough space for the memory requested. The more fragmented memory becomes the longer this can take.
.Net reserves a contiguous region of memory that it will use for the managed heap.Frameworkalso maintains a pointer to the location where the next object will be allocated.
Application creates some objects. If it will fit the location the NewObjPtr points to is used for the new object, the constructor of the new object is called and the address of the object is returned to the calling program.NewObjPtr is advanced beyond the new object and points to where the next object will be created in the heap.
Deep Dumpster Diving
Deep Dumpster DivingA close look at .Net garbage collection<br />Ronn Black<br />October 2009<br />
Optimizations<br />Generations<br />Newly created objects tend to have short lives.<br />The older an object is, the longer it will survive. <br />Groups objects by age and collects younger objects more frequently than older objects.<br />All objects added to heap are in generation 0.<br />When an object survives the first garbage collection it is promoted to generation 1.<br />When garbage collection is triggered survivors from generation 1 are promoted to generation 2 and generation 0 survivors are promoted to gen 1.<br />As objects "mature", they are moved to the next older generation until they reach gen 2. <br />
Types of Memory Leaks<br />Managed leaks – persistent object holds a reference to an object expected to be garbage collected.<br />Unmanaged leaks - using unmanaged resources, dll’s or COM objects that leak memory.<br />