Garbage Collection in .NET – Workstation vs. Server GC.

Garbage Collection in .NET – Workstation vs. Server GC.

11/06/2014 00:22:17

So, I’m reading the largely excellent “Writing High-Performance .NET Code” by @benmwatson at the moment, and I wanted to share something that’s expressed especially clearly, that I find ambiguous in many of the official docs.

The garbage collector in .NET is treated by a vast majority of devs as a thing of mystery – and one of those mysterious options is “Do you want to run the GC in ‘Workstation’ or ‘Server’ mode?

Workstation GC

  • All GCs happen on the same thread that triggers the collection
  • They’re all run at the same priority
  • A full suspension occurs before collection

Server GC

  • Creates a dedicated thread for each logical processor or core
  • Each of these threads run at the highest priority
  • These threads sleep between collections
  • A memory heap is created for each GC thread
  • Garbage collections happen in parallel due to multiple heaps

For both, from .NET 4.5

  • A background thread exists for generation 2 garbage collection
  • This dedicated thread can be disabled

As a result

  • Server GC has the lowest latency
  • Choose Server GC if you have a dedicated box for your application
  • If you have many managed processes be more wary - the abundance of high priority background threads could cause a performance problem.
  • You can mitigate this contention by setting process affinity to specific logical processors, at this point the CLR will only create GC threads and managed heaps for the logical processors your process is affinitized to.

TL;DR: Choose server, unless you have *lots* of managed applications on the box. Always choose server in a dedicated one-machine-per-app environment.

Also, read the book!