Search code examples
performancegarbage-collection

Does garbage collection affect performance?


I am just reading about the performance of several programming languages, and I noticed that garbage collection gets mentioned fairly often. Does garbage collection affect the performance of a language at all? If yes, how?


Solution

  • One thing to keep in mind here is a language without garbage collection must still both allocate and free objects. Garbage collection allows the "free" part of the cycle to happen in batches, and at times when the application is otherwise relatively idle. In an environment with minimal memory constraints, most collections might even defer until the program is completed. In other words, a highly-efficient garbage collector has the potential to be faster than the common practice in a traditional platform... not that we're quite that far yet, but this is improving all the time.

    The trick is when garbage collections do occur, the collector must still spend resources doing the analysis of what is reachable and what isn't, or what has a reference count > 0 and what doesn't (depending on the type of collector). That is a real performance penalty. Additionally, this process does tend to briefly interrupt normal execution.

    The interruptions can especially be a significant factor in applications that are sensitive to latency issues. This happens to include the common scenario of serving web content. Fortunately, there are also now garbage collector modes to reduce this impact.

    The result is for most garbage collected platforms, the collector is one factor to consider when evaluating performance. The net effect of the garbage collector may be minimal — or even a net positive! — over the life of an application session, but there can short-lived periods where there is significant negative impact, and it's important to be aware of how to mitigate those issues.


    The above is all platform agnostic. Personally, I'm most familiar with the .Net environment. In that specific area, and talking specifically about the web service challenges mentioned previously, the things to know are to make sure you're using the GC's server mode, that you're up-to-date with the latest version of the framework (there is lots of on-going performance work that has born some fruit in this area in recent releases), that you avoid the large object heap as much as possible, that you do whatever you can to reduce allocations in the first place, and that you have appropriate monitoring in place.