Skip to content

Skip locals init C# 9.0performance

Prevent the CLR from zeroing local variables for performance.

The C# compiler normally emits a .localsinit flag that forces local variables and stacks to be zero-initialized by the CLR.

This is usually redundant as C# uses definite assignment in all but a few unsafe scenarios (covered below).

In C# 9.0 the SkipLocalsInitAttribute may be used to suppress this flag for some small performance gains. Applying it to a method affects all that methods local variables including any local functions or lambdas it declares. If applied to a type it applies to all methods on that type, when applied to a module then to all methods in that assembly.

Notes

  • Care must be taken for the scenarios in which C# does not enforce definite assignment and might contain uninitialized data. They are unsafe code, stackalloc usages, and P/Invoke scenarios

More information