Skip to content

Inline arrays C# 12.0performance

Annotate a struct with InlineArray for optimized performance.

C# 12.0 introduces the InlineArrayAttribute which allows a struct to be annotated as an inline array. This allows the compiler to optimize performance by eliminating runtime bounds and type checking.

Code

C#
[System.Runtime.CompilerServices.InlineArray(255)]
public struct Buffer
{
    private char _element0;
}

// Faster performance because NO range and type checking
var buffer = new Buffer();
for (int i = 0; i < 255; i++)
{
    buffer[i] = (char)i;
}
C#
// Slower performance due to range and type checking
var buffer = new char[255];
for (int i = 0; i < 255; i++)
{
    buffer[i] = (char)i;
}

More information