Skip to content

Instantly share code, notes, and snippets.

@j0sh
Created March 28, 2024 00:02
Show Gist options
  • Save j0sh/3486fb33ab972f3ba75bfd63c9d038ad to your computer and use it in GitHub Desktop.
Save j0sh/3486fb33ab972f3ba75bfd63c9d038ad to your computer and use it in GitHub Desktop.
Slice vs []byte equality in golang
package main
import (
"bytes"
"crypto/rand"
"slices"
"testing"
)
// generateRandomByteSlice generates a random byte slice of the given size.
func generateRandomByteSlice(size int) []byte {
slice := make([]byte, size)
if _, err := rand.Read(slice); err != nil {
panic("failed to generate random byte slice: " + err.Error())
}
return slice
}
var (
// Generate 5KB random byte slices once for all benchmarks to use.
a = generateRandomByteSlice(5 * 1024) // 5KB
)
// BenchmarkBytesEqual benchmarks the bytes.Equal function for the same 5KB random byte slices.
func BenchmarkBytesEqual(b *testing.B) {
b.ResetTimer() // Ensure the setup time is not included.
for i := 0; i < b.N; i++ {
_ = bytes.Equal(a, a)
}
}
// BenchmarkSlicesEqualByteSlice benchmarks the slices.Equal function for the same 5KB random byte slices.
func BenchmarkSlicesEqualByteSlice(b *testing.B) {
b.ResetTimer() // Reset the timer to exclude setup time from the benchmark.
for i := 0; i < b.N; i++ {
_ = slices.Equal(a, a)
}
}
$ go test -bench Equal
goos: darwin
goarch: amd64
pkg: otpguard
cpu: Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
BenchmarkBytesEqual-12 1000000000 0.2457 ns/op
BenchmarkSlicesEqualByteSlice-12 482109 2485 ns/op
PASS
ok otpguard 2.780s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment