Skip to content

proposal: cmd/compile: allow optimizing struct field alignment at compile time #81874

Open

Description

@gitsomebit

Proposal Details

I use fieldalignment to get the best possible memory layout for structs.

One downside is that the optimal field order for memory usage is not necessarily the most readable order for humans. Fields that belong together logically may introduce additional padding.

For example, I may naturally want to think about a struct like this:

type Resource struct { // struct with 104 pointer bytes could be 72
	ID   int
	Name string
	Kind string

	CreatedAt int64
	UpdatedAt int64

	Priority int
	Assigned map[string]string
	Tasks    []string

	Tags []string
}

But I do not want the order of the fields to constrain fieldalignment. I still want to use the optimal layout for the entire struct, even if that means rearranging them.

It would be useful to have a struct-level annotation that explicitly communicates this intent.

For example:

// fieldalignment:optimize
type Resource struct {
	ID   int
	Name string
	Kind string

	CreatedAt int64
	UpdatedAt int64

	Priority int
	Assigned map[string]string
	Tasks    []string

	Tags []string
}

For a struct marked this way, fieldalignment could assume that field order has no logical significance and freely reorder all fields for the optimal memory layout.

The exact comment syntax is not important to me. The main idea is to provide an explicit opt-in that means:

For this struct, I do not care about logical field order. Use the optimal layout

I think this would make it easier to distinguish structs where source ordering should be treated conservatively from structs where unrestricted reordering is desirable.

Activity

  1. added this to the Proposal milestone on Sep 30, 2026
  2. ianlancetaylor commented on Sep 30, 2026

    @ianlancetaylor
    Contributor

    Sounds like a dup of #53048.

  3. changed the title [-]proposal: fieldalignment: allow optimizing struct fields at compile time[/-] [+]proposal: cmd/compile: allow optimizing struct field alignment at compile time[/+] on Sep 30, 2026
  4. seankhliao commented on Sep 30, 2026

    @seankhliao
    Member

    #10014 seems to be the last time this was discussed in depth?

  5. marcelloh commented on Sep 30, 2026

    @marcelloh

    I'm all for this idea, because it keeps the source human-readable, and the outcome cpu & memory optimized.
    If an external tool can do this, it can't be hard to fix this in the compiler.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions