Search code examples
c#linqforeachconventionsroslyn

"Avoid allocations in compiler hot paths" Roslyn Coding Conventions


I've been reading through the Contributing to Roslyn section of the .NET Compiler Platform ("Roslyn"), and I came across the guidelines for coding conventions. I understand most of the coding conventions and why they would ask for it. But I don't understand what they mean by this:

  • Avoid allocations in compiler hot paths:
  • Avoid LINQ.
  • Avoid using foreach over collections that do not have a struct enumerator.

What is a "compiler hot path"? And why should I avoid using LINQ and avoid doing a foreach over collections that do not have a struct enumerator?


Solution

  • Compiler hot paths are code execution paths in the compiler in which most of the execution time is spent, and which are potentially executed very often.

    The reason for avoiding (heap) allocations in these code paths is that allocations may trigger a garbage collection, which may cause sudden, extreme performance deteriorations. These should obviously be avoided in very commonly executed code paths.

    Linq and foreach are singled out because these will implicitly allocate memory – unless your GetEnumerator returns a struct, which will not cause heap allocations.