From Dave Cheney's article about struct comparaison code generated by Go compiler (https://dave.cheney.net/2020/05/09/ensmallening-go-binaries-by-prohibiting-comparisons):
Padding exists to ensure the correct field alignments, and while it does take up space in memory, the contents of those padding bytes are unknown. You might assume that, being Go, the padding bytes are always zero, but it turns out that’s not the case–the contents of padding bytes are simply not defined. Because they’re not defined to always be a certain value, doing a bitwise comparison may return false because the nine bytes of padding spread throughout the 24 bytes of S [a previously defined struct with padding] may not be the same.
The Go compiler solves this problem by generating what is known as an equality function. In this case S‘s equality function knows how to compare two values of type S by comparing only the fields in the function while skipping over the padding.
EDIT: the same source states that struct {int64, int64}
are compared using memory compare, while struct {int64, int8}
requires a custom function because of padding, enlarging the resulting binary.
Why doesn't Go compiler solve this by defining padding bytes content, and so it can compare using something like memcmp
instead?
EDIT: Is there any overhead in zeroing or comparing one word instead of one byte (e.g.: zeroing and comparing 16 bytes instead of 9 in the previous struct {int64, int8}
example)?