Skip to content

Investigate using Auto layout for structs in the framework #64261

Closed as not planned
@GSPP

Description

@GSPP

By default, the C# compiler marks structs [StructLayout(LayoutKind.Sequential)]. I believe the historic reason for this is that structs were assumed to be mainly for interop. Unfortunately, this can cause unnecessary padding (and possibly other inefficiencies?).

The default in the C# language cannot be changed because large bodies of existing code depend on this behavior.

Even if the struct itself does not benefit from Auto, the runtime can rearrange fields together with surrounding structs: #7720 (comment). It's therefore not enough to look at a struct definition to conclude that it is not beneficial to mark it Auto. Profitability depends on usage as well.

I wonder if it can be considered a performance best practice to routinely mark all non-interop structs as LayoutKind.Auto. This strategy does not seem to have a downside except for the code clutter that this brings.

Would it be worth adopting a policy in which all eligible structs are marked as Auto? Should there be an analyzer for that?

This policy would be in contrast to making case-by-case decisions. The benefit is simplicity and ease of code review. "If the attribute is missing, it's a bug."

I loaded all system assemblies and made lists for how the struct layout is currently set:

5.0.8 Auto.txt
5.0.8 Explicit.txt
5.0.8 Sequential.txt

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    Status

    No status

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions