reorder fields to reduce size of objects #3008
Closed
+25
−23
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This PR re-orders some fields in structs in order to reduce the size in bytes that the struct takes up in memory. Go is sensitive to the exact ordering of fields. I have not done any extensive profiling to see if this change makes a significant difference of memory usage at runtime, but this change is not harmful (unless you consider the ordering of fields useful for documentation purposes).
https://golangprojectstructure.com/how-to-make-go-structs-more-efficient/
https://go101.org/article/memory-layout.html
A tool exists, as noted in the first blog post link, that can find inefficient orderings of fields and provide the correct order.
https://cs.opensource.google/go/x/tools/+/refs/tags/v0.26.0:go/analysis/passes/fieldalignment/cmd/fieldalignment/main.go
I ran this tool on all the code in go-libp2p and fixed the 4 highest offenders.
Before:
After:
Note that there are many more structs to fix, but the savings is moderate for them (under 100 bytes of savings for each struct).