Tuning the garbage collector to the specific context of the particular application can significantly improve the performance of both non-threaded and multi-threaded applications. In this post I discuss the gcConcurrent and gcServer settings which allow you to exercise some control how the Garbage Collector operates.
Articles in This Series
Part 1 - Basic Housekeeping
Part 2 - Improving Performance Through Stack Allocation
Part 3 - Increasing the Size of the Stack
Part 4 - Garbage Collector Settings
Part 5 - Changing Your Garbage Collector Settings on the Fly
Concurrent Garbage Collection, In My Program?
By default the CLR Garbage Collector operates concurrently. What this means is it operates in a separate thread and periodically blocks the operation of the application thread. This is the best behavior for most windows applications as it allows the interface to update while the Garbage Collector operates.
However, you may not want the overhead of all this context switching. If your application is console based or does not need to keep updating an interface, you can see significant performance gains by not having your application’s Garbage Collector in a separate thread.
So, How Do I Make My Garbage Collector Not Concurrent?
In your application’s app.config file set the gcConcurrent tag to false:
You should also know:
- The default value is true and so that setting will have no effect.
- In ASP.NET applications you do not need to change this setting.
- On machines with only one processor this has no effect.
What If I Have Lots of Threads?
On the other side of the coin, you could have an application with many threads on a computer with many cores. In this case your performance may be limited by the single Garbage Collector thread’s ability to allocate or deallocate fast enough. Your threads would be waiting on your Garbage Collector.
The solution to this problem is to have many Garbage Collectors, each with their own thread. This would remove the limitation in exchange for a small amount of overhead. In .NET, this is called Server Mode.
When the Garbage Collector is in Server Mode there is one Garbage Collector thread per core and one set of heaps per garbage collector thread. The application threads allocate from them in a round-robin fashion.
How Do I Enable Server Mode?
In your application’s app.config file set the gcServer tag to true:
You should also know:
- The default value is false and so that setting will have no effect.
- This setting should be fastest on computers with more than two cores.
- You can use the GCSettings.IsServerGC property to check if this type of garbage collection is enabled.
About the AuthorFollow on Twitter More Content by Rick Minerich