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.
Code
C#
[SkipLocalsInit]
static void ProcessBuffer()
{
Span<byte> buffer = stackalloc byte[256];
// buffer contents are NOT zero-initialized — slightly faster
Fill(buffer);
Send(buffer);
}C#
static void ProcessBuffer()
{
Span<byte> buffer = stackalloc byte[256];
// CLR always zero-initializes the buffer before use
Fill(buffer);
Send(buffer);
}Notes
- Care must be taken for the scenarios in which C# does not enforce definite assignment and might contain uninitialized data. They are
unsafecode,stackallocusages, and P/Invoke scenarios