However, for all that the garbage collector is a brilliant piece of software engineering, sometimes collections still occur at inconvenient times. If you need to write high performance, real-time code, in addition to measuring performance using tools like ANTS Performance Profiler, you generally want to try to avoid GC collections during times where execution speed is critical. For example: in an XNA game, you want to avoid collections during gameplay to prevent visual glitches in your animations; in a real time financial analysis and trading application, you want to avoid collections between when you begin analyzing incoming data and when you finish executing an algorithmically-controlled trading decision based on that data. Of course, sometimes GC collections at inconvenient times are unavoidable, and in those situations it is best to instead try to minimize the duration of individual collections (See: http://blogs.msdn.com/b/shawnhar/archive/2007/07/02/twin-paths-to-garbage-collector-nirvana.aspx). This article focuses mainly on avoiding collections, and while there is some overlap between optimizing to minimize GC frequency and optimizing to minimize GC latency, the two goals can also collide. This is certainly the case with object pooling, which can be very helpful with reducing frequency, but is almost guaranteed to increase latency (especially with non-generational GCs).
As you’re no doubt already aware, the GC runs automatically when certain defined conditions are met, and the specific conditions vary depending on the common language runtime in which the program is running. The .NET 4.0 Framework CLR has different conditions than the .NET 3.5 Compact Framework CLR, for instance. Nonetheless, the GCs of every CLR that I am familiar with all run a collection when a certain number of bytes have been allocated since the previous collection, and it’s this triggered collection that we will consider.
Read more: Simple-talk
QR: