by yawaramin · 3y ago · 0 comments
This is interesting because in certain cases it can be a performance hit when comparing structs which have been declared in alignment order to save memory. Simple example:
type t struct {
a int64
b int32
}
t1 := t{a: 1, b: 2}
t2 := t{a: 1, b: 3}
same := t1 == t2
When comparing `t1` and `t2`, the runtime will first compare the `a` fields, which are the same, then the `b` fields, which will differ. Only after doing both comparisons will it figure out that they're different. But the `a` fields are int64, so it has to traverse these large data types before finally getting the answer.Of course this is a trivial example, in real-world cases structs can have many more fields with much larger contents. The point is that the optimal ordering for alignment, and the optimal ordering for comparison, seem to be different.
This is more of a constraint if the struct contains a comparison that can panic. The panic must happen in order or not at all depending how the fields are listed.
type t struct {
a int64
b any
}
Should not panic on b if a values are already different.