Swift lays out stored properties in declaration order, so a poorly ordered struct silently wastes memory and bandwidth. Nothing in the toolchain tells you where that happens. This pitch proposes an off-by-default diagnostic group that answers one question: where do my struct layouts leave room for improvement?
Enable the group, build, and every struct whose stride a different order would shrink is reported together with the possible saving. The diagnostic changes no layout and suggests no order: the compiler points out the opportunity, the developer decides. Source order can carry intent, such as fields that are read together, so that decision belongs to the author. Intentional layouts are opted out per type through @diagnose and a written reason.
Motivation
The same three fields take 24 instead of 16 bytes per element (50 % more) when the large field is not first, and a bandwidth-bound loop pays that 1.5× directly. Measured with Swift 6.4 (-O, release build) on an Apple M4:
struct Bad { // stride 24
var isActive: Bool
var value: Int64
var isVisible: Bool
}
struct Good { // stride 16
var value: Int64
var isActive: Bool
var isVisible: Bool
}
| Type | size | stride | Padding per element | Sum of value, 2 M elements (p50 per element) |
|---|---|---|---|---|
[Bad] |
17 B | 24 B | 14 B | 0.33 ns |
[Good] |
10 B | 16 B | 6 B | 0.22 ns |
The slowdown follows the stride ratio (24 / 16 = 1.5×; we measured 1.5–1.7× across runs) because the loop waits on memory, not arithmetic. Larger types show the same pattern: a Sprite with two Floats, a UInt32, a String and a Bool takes 40 bytes as written and 32 bytes with the String first.
Nothing in the toolchain points this out today. The compiler keeps declaration order (TypeLayout.rst), SwiftLint cannot see type sizes, and DWARF-based tools such as pahole do not work because Swift's debug info carries no member offsets for Swift structs (checked with dwarfdump). The only safeguard is a hand-written #expect(MemoryLayout<T>.stride == …) per type, and only for types someone already suspects.
Proposed diagnostic
A new diagnostic group, tentatively AvoidablePadding, suppressed by default and enabled with -Wwarning AvoidablePadding (SE-0443) or the SwiftPM warning settings (SE-0480).
Rule. For a struct whose stored properties all have a layout known at compile time:
- Let S be the stride of the struct as declared.
- Let S* be the stride the compiler's own layout algorithm produces with the stored properties sorted by alignment, largest first.
- If S* < S, emit the warning on the struct.
The sorted order is only used internally to prove that a better layout exists. It is never shown to the user, and the diagnostic makes no claim that S* is the minimum.
Message.
warning: the stride of 'Bad' could shrink from 24 to 16 bytes by reordering its stored properties [#AvoidablePadding]
Which fields to move, and whether to move them at all, stays with the author. The rule compares stride, because stride is what arrays, UnsafeMutablePointer.allocate(capacity:) and memory bandwidth pay for. Padding that no order can remove is never reported, which avoids the noise -Wpadded is known for.
Intentional layouts: @diagnose with a reason
Some layouts trade stride for locality on purpose, for example fields read together kept on one cache line, or producer and consumer indices kept apart to avoid false sharing. SE-0522 (implemented in Swift 6.4) already provides the opt-out, and its reason: parameter records why the layout is intentional, right at the type:
@diagnose(AvoidablePadding, as: ignored,
reason: "head and tail stay on separate cache lines to avoid false sharing")
struct RingIndices {
var head: Atomic<Int>
var padding: InlineArray<15, Int>
var tail: Atomic<Int>
}
The same attribute could also work the other way round, provided a default-suppressed group can be enabled per scope (see open question 2). A project that does not enable the group module-wide could then opt in for its hot-path types:
@diagnose(AvoidablePadding, as: warning)
struct Particle {
// …
}
So the feature needs no new attribute and no new flag syntax: one diagnostic group, controlled by the mechanisms Swift 6.1 and 6.4 already ship. We checked that Swift 6.4 accepts @diagnose(<group>, as: ignored, reason: "…") on a struct declaration without an experimental flag and that it suppresses the group only inside that type.
Scope and limitations
The warning only fires where the compiler knows every field's layout; everything else is silently skipped.
| Case | Behaviour | Why |
|---|---|---|
| Struct with fields of known, fixed layout | Diagnosed | The compiler can compute both strides |
Field of a resilient type (library evolution, not @frozen) |
Containing struct skipped | Size is only known at run time |
| Field of a generic parameter or opaque type | Containing struct skipped | Layout depends on the substitution |
Generic @frozen struct |
Skipped | No declaration order is right for every substitution |
| Struct imported from C | Never diagnosed | Layout is fixed by the C ABI |
@frozen public struct in a library-evolution module |
Diagnosed, note says reordering is ABI-breaking once shipped | Most useful before the first release |
| Classes, enums with payloads | Out of scope for now | Instance size and payload layout follow different rules |
The computation must use Swift's layout algorithm, not C's. Swift distinguishes size from stride and places a field in the tail padding of a preceding struct-typed field, so a C-style estimate would report false positives for nested structs.
Target dependence. Layout depends on the target, so a struct that is clean on one platform can be reported on another, and in general there may be no single order that is clean on all targets. The diagnostic reports for the target being compiled. This is one more reason the group is off by default: projects that don't want target-dependent warnings simply don't enable it, and those that do want to know about such cases can.
Compile-time cost
When the group is disabled, the check is skipped entirely and costs nothing. When enabled, it computes one additional layout per struct with a fixed layout, from field type infos the compiler has already computed: a sort by alignment plus one layout computation. The diagnostic deliberately does not search for the optimal order: without C's size-multiple-of-alignment rule, no sub-quadratic algorithm for it is known.
Alternatives considered
Automatic reordering by the compiler. Reordering non-frozen structs has been discussed since 2016. It is not the goal of this pitch: source order is today the only tool developers have for locality, so it may carry intent, and it should only change where it makes a real difference and with the author's agreement. The diagnostic does not depend on reordering and does not rule it out.
An explicit layout attribute. An attribute such as @layout(compact) would keep today's behavior as the default and make a different layout an explicit opt-in. This is complementary, not an alternative: the attribute is a way to change a layout, the diagnostic is a way to find where a change pays off. Without the diagnostic, nobody knows which types would benefit from such an attribute. And for types that must keep their declared order, such as @frozen types that have already shipped, or where moving one field by hand is preferable to a different layout mode, the diagnostic is the only help. If such an attribute is pitched, a later version of the diagnostic could point to it directly.
A portable-layout check. A check that a type has the same layout on every target would give portable results, but it would have to forbid pointers, Int and other target-dependent types. It is aimed at binary serialization and complements this diagnostic rather than replacing it.
A -Wpadded-style warning. Reporting all padding is known to be noisy, because much of it cannot be removed. This pitch only reports padding that a reorder can remove.
Doing nothing. Projects can assert strides in tests today, but only for types someone already suspects, and the expected value has to be worked out by hand.
Future directions
Size, not only stride. A type stored inside another type contributes its size, not its stride, because Swift places the next field in its tail padding. A reorder that leaves a type's own stride unchanged can therefore still shrink every type that contains it:
struct Inner { // size 8, stride 8
var a: Int32
var b: Bool
var c: Int16
}
struct Outer { // size 9, stride 12
var inner: Inner
var flag: Bool
}
Swapping b and c keeps Inner at stride 8 but reduces its size to 7, which brings Outer down to stride 8, a third less per element. The rule above does not report this case. It could be covered by a separate group, for example AvoidableTailPadding, so that the main group stays quiet.
A fix-it. Since the diagnostic suggests no order, there is nothing for a fix-it to apply. A follow-up could offer one when the memberwise initializer is not public, where reordering fields is not an API change.
Pointing to a layout attribute, if one is added (see Alternatives considered).
Open questions for the compiler team
- Where can this be diagnosed? As far as we understand, concrete struct layout is computed late, during IRGen, where warnings are unusual. Is there an earlier point (type lowering, SIL) that knows fixed layouts, or is an IRGen-time warning acceptable here? An IRGen-time warning would not appear during type-checking-only runs such as SourceKit.
- Default-suppressed groups. SE-0522 states that default-suppressed warnings can be enabled with
-Wwarning. Can a new group be declared default-suppressed, and does@diagnose(Group, as: warning)enable such a group inside one type? - Threshold. Clang's checker only reports above a configurable threshold. Diagnostic groups currently take no parameters. Should there be a fixed minimum saving, or is any stride reduction worth reporting for an opt-in group?
- Name.
AvoidablePadding,StructPaddingorSuboptimalLayout?
Prior art and prototype
Clang has shipped a similar idea since 2015: the static analyzer's opt-in checker optin.performance.Padding reports records "that could reduce [their] padding by reordering the fields", with a configurable threshold (AllowedPad, default 24 bytes). It skips cases with ABI complications, much like the scope table above.
| Tool | What it reports | Noise |
|---|---|---|
GCC / Clang -Wpadded |
Any padding at all | High: also unavoidable padding |
Clang optin.performance.Padding |
Padding a reordering would remove, above a threshold | Low |
| This pitch | The stride saving a reordering could achieve | Low |
Rust (repr(Rust)) |
Nothing: the compiler reorders fields itself | None |
The rule is cheap to compute and easy to prototype today. A test helper using Mirror, MemoryLayout and _openExistential reproduces the proposed result for these example types. Its output still lists one possible order, which the proposed diagnostic deliberately omits (messages translated):
⚠ Bad: stride 24, possible 16 with order ["value", "isActive", "isVisible"]
✔ Good: stride 16 is optimal
⚠ Sprite: stride 40, possible 32 with order ["name", "x", "y", "color", "flag"]
The prototype needs a sample value of each type and cannot see tail-padding reuse in nested structs; the compiler has neither limitation.
Sources
- Joe Groff on swift-evolution, January 2016: "We do plan to change Swift's default layout strategy to minimize padding"
- Swift Forums: Optimal stored property packing (February 2024)
- Swift Forums: What are the benefits of minimizing the MemoryLayout size/stride of a struct? (August 2024)
- swift/docs/ABI/TypeLayout.rst: fields laid out in declaration order
- SE-0260 Library Evolution for Stable ABIs:
@frozenlayout guarantee - SE-0443 Precise Control Flags over Compiler Warnings
- SE-0522 Source-Level Control Over Compiler Warnings:
@diagnose, Swift 6.4 - LLVM D14779: Adding checker to detect excess padding in records:
optin.performance.Padding - Red Hat Developer: How to avoid wasting megabytes of memory a few bytes at a time:
-Wpaddedandpahole