Created
November 22, 2021 15:11
-
-
Save tzaffi/021a382c9a7421e722be4e246ffb11a9 to your computer and use it in GitHub Desktop.
Go: Faster to assign / swap slice fields in structs than parent structs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type aStruct struct { | |
aSlice []byte | |
} | |
func BenchmarkStructSwapping(b *testing.B) { | |
ssize := 500 | |
b.Run("naive", func(b *testing.B) { | |
theStructs := make([]aStruct, b.N*2) | |
for i := 0; i < b.N; i++ { | |
theStructs[i].aSlice = make([]byte, ssize) | |
theStructs[i+b.N].aSlice = make([]byte, ssize) | |
} | |
b.ResetTimer() | |
for i := 0; i < b.N; i++ { | |
theStructs[i], theStructs[i+b.N] = theStructs[i+b.N], theStructs[i] | |
} | |
}) | |
b.Run("inslice", func(b *testing.B) { | |
theStructs := make([]aStruct, b.N*2) | |
for i := 0; i < b.N; i++ { | |
theStructs[i].aSlice = make([]byte, ssize) | |
theStructs[i+b.N].aSlice = make([]byte, ssize) | |
} | |
b.ResetTimer() | |
for i := 0; i < b.N; i++ { | |
theStructs[i].aSlice, theStructs[i+b.N].aSlice = theStructs[i+b.N].aSlice, theStructs[i].aSlice | |
} | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The following benchmark results show that swapping 500 byte slices inside of a struct is around 5x faster than swapping the container structs on an Intel based Macbook Pro.