.NET FundamentalsGarbage Collection
Woody [email protected]
Why Multi Generational?
Concurrent/Synchronousaka workstation and server
• Concurrent garbage collection is used in desktop applications
• Synchronous is used in server applications such as ASP.NET by default.
• Concurrent mode, .NET will try to avoid stopping the running program while a collection is in progress
• In synchronous mode, .NET will suspend the running application while the garbage collector is running
The good
• Cost of doing an allocation is extremely low• You don’t manage memory or pointers!
Issues to watch for
• Too Many Allocations– String.Split– String concatenation
• Too-Large Allocations• Too Many Pointers– Transitory objects with a lot of interdependencies
• Too Many Roots• Too Many Almost-Long-Life Objects
What's wrong with this?
string x = ""; for (int y = 0; y < 100; y++) { x += this.randomString(); }
Strings are immutable objects in the CLR!
Use StringBuilder!
string x = "";StringBuilder y = new StringBuilder();
for (int i = 0; i < 100; i++){ y.Append(this.randomString());}
x = y.ToString();
Finalization
• Objects that need finalization live longer than objects that do not
• Objects that need finalization cause collateral damage
• Objects needing finalization create work for the finalizer thread
IDisposable and Dispose
• This interface provides an alternative method for reclaiming resources whose lifetime is well known to the programmer
class X: Idisposable {public X() { //initialize resources}~X() { //release resources }public void Dispose() { // this is the same as calling ~X() Finalize(); // no need to finalize later System.GC.SuppressFinalize(this); } }
Weak References
• http://msdn.microsoft.com/en-us/library/system.weakreference.aspx
Induced Collections
• GC.Collect – Just don’t do it!
• Use GCCollectionMode if you must!– Default– Forced– Optimized
Consider
• Allocate all of the memory to be used with a given data structure at the same time
• Remove temporary allocations that can be avoided
• Minimize the number of times object pointers get written
• Reduce the density of pointers in your data structures.
• Make limited use of finalizers!