Re:Optimizing Rust Struct Size
by glandium on Saturday April 15, 2017 @06:45PM
(#14123252)
While this might be pretty rare, I can see how one would want some fields in large structs to stay close to one another to stay in the same cache lines. If the compiler moves things at will, you lose the ability to do such things... I guess you could still use repr(C) and optmize manually, then...
[ Parent
| on HN ]
One thing to consider in this respect is the optimisation won't/can't separate out the subfields of a field, meaning `struct Foo { ... x: SomeStruct ... }` will reorder x as a whole, keeping the fields of SomeStruct together. Fields that are accessed together often could theoretically be pulled out into a separate type, which, depending on the codebase, may be a nice idea anyway. (Similarly, one could group the fields in a tuple, `x: T, y: U` => `xy: (T, U)`, although this is... rather ugly.)
This property also ensures a (hypothetical) type like `CachePadded<T>`, which keeps a value of type T in its own cache line, works as expected.
> I guess you could still use repr(C) and optmize manually, then…
You always had to, the compiler explicitly never guaranteed layout for repr(rust), it just didn't perform any optimisation yet before TFA's changes.
You could also have the reverse. Pushing volatile fields or objects into separate cache lines to avoid contended access.