Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[EC81] Rule proposal : Specify struct layouts #18

Closed
vdebellabre opened this issue Mar 23, 2024 · 0 comments · Fixed by #19
Closed

[EC81] Rule proposal : Specify struct layouts #18

vdebellabre opened this issue Mar 23, 2024 · 0 comments · Fixed by #19
Assignees
Labels
🗃️ rule rule improvment or rule development or bug 🚀 enhancement New feature or request

Comments

@vdebellabre
Copy link
Collaborator

vdebellabre commented Mar 23, 2024

Category : Performance

Severity : Warning

Why is this an issue ?

Structs that don't contain reference types (directly nor indirectly) have the Sequential layout by default. This is to prevent breaking any project that uses interop code and requires that the fields stay ordered. In other cases however, field reordering is usually fine and there are little reasons to use the Sequential layout over the Automatic one, as it will optimize the layout for you, potentially saving memory and improving performance in the process.

You can read a much more in-depth analysis of struct packing here : http://www.catb.org/esr/structure-packing/

When can it be ignored ?

It can be ignored if you know you require the Sequential layout for all of your structs, most likely for interop purposes.

Examples

public struct MyStruct // Compliant, no field
{
}

public struct MyStruct // Compliant, only one field, no ordering possible
{
    public int A;
}

public struct MyStruct // Non compliant, specify the layout. Will take 24 bytes because of Sequential
{
    public int A;
    public double B;
    public int C;
}

[StructLayout(LayoutKind.Sequential)]
public struct MyStruct // Compliant, specified layout. Will take 24 bytes because of Sequential
{
    public int A;
    public double B;
    public int C;
}

[StructLayout(LayoutKind.Auto)]
public struct MyStruct // Compliant, specified layout. Will take 16 bytes thanks to Auto
{
    public int A;
    public double B;
    public int C;
}

public struct MyStruct // Compliant, string is a reference type, LayoutKind.Auto will be forced. Will take 16 bytes
{
    public int A;
    public string B;
    public int C;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
🗃️ rule rule improvment or rule development or bug 🚀 enhancement New feature or request
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant