Skip to content

re-order struct fields for better performance and memory usage #168

Open
@andrewrk

Description

@andrewrk

In Zig, you have no guarantee about the memory layout of a struct unless you make a struct packed or export.

Take advantage of this:

  • align fields appropriately for fast access. Allow explicitly setting the minimum alignment per field.
  • re-order smaller fields to fit in alignment gaps for smaller memory usage
  • gaps created by maybe types, error unions, and other containers can be filled by smaller types
  • put large fixed size arrays at the end for better cache performance of the rest of the struct fields
  • to enable the same function code to work for multiple specialized data types. For example, a field that uses a parameterized type might be moved to the last position, so that functions which only reference fields before that one can share the same codegen.

Provide safety against incorrect assumptions about field order:

  • provide builtin function @container_base(inline T: type, field_name_symbol, field_pointer) -> &T (better name suggestion welcome @thejoshwolfe). This function takes a pointer to a container field, the container type, and a symbol which is the name of the field, and returns a pointer to the struct. Programmers should use this builtin instead of futzing around with pointers to go from a field pointer to the container base pointer.
  • in debug mode, order fields backwards from declaration order. This ensures that an incorrect assumption will not work in debug mode. This safety trick may turn out to be too expensive. If so, we will do the same field ordering logic in debug mode and release mode.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementSolving this issue will likely involve adding new logic or components to the codebase.frontendTokenization, parsing, AstGen, Sema, and Liveness.optimization

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions