go-libp2p icon indicating copy to clipboard operation
go-libp2p copied to clipboard

reorder fields to reduce size of objects

Open kazzmir opened this issue 4 months ago • 3 comments

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

$ ~/go/bin/fieldalignment ./...

I ran this tool on all the code in go-libp2p and fixed the 4 highest offenders. Before:

/home/ubuntu/kazzmir-go-libp2p/p2p/host/resource-manager/scope.go:33:20: size is 160 but could be 80 diff=80
/home/ubuntu/kazzmir-go-libp2p/p2p/net/connmgr/connmgr.go:29:19: size is 2240 but could be 2152 diff=88
/home/ubuntu/kazzmir-go-libp2p/p2p/host/resource-manager/extapi.go:30:26: size is 120 but could be 24 diff=96
/home/ubuntu/kazzmir-go-libp2p/p2p/host/resource-manager/limit_defaults.go:349:25: size is 616 but could be 40 diff=576
/home/ubuntu/kazzmir-go-libp2p/p2p/host/resource-manager/limit_defaults.go:514:26: size is 616 but could be 40 diff=576
/home/ubuntu/kazzmir-go-libp2p/p2p/http/auth/internal/handshake/server.go:86:32: size is 1384 but could be 312 diff=1072
/home/ubuntu/kazzmir-go-libp2p/p2p/host/resource-manager/limit_defaults.go:24:25: size is 1192 but could be 40 diff=1152

After:

/home/ubuntu/kazzmir-go-libp2p/p2p/host/resource-manager/scope.go:33:20: size is 160 but could be 80 diff=80
/home/ubuntu/kazzmir-go-libp2p/p2p/net/connmgr/connmgr.go:29:19: size is 2240 but could be 2152 diff=88
/home/ubuntu/kazzmir-go-libp2p/p2p/host/resource-manager/extapi.go:30:26: size is 120 but could be 24 diff=96

Note that there are many more structs to fix, but the savings is moderate for them (under 100 bytes of savings for each struct).

kazzmir avatar Oct 17 '24 06:10 kazzmir