Skip to content

Instantly share code, notes, and snippets.

@yihuang
Last active December 24, 2022 16:07
Show Gist options
  • Save yihuang/c783648d8778e5e13cf08148274fba2e to your computer and use it in GitHub Desktop.
Save yihuang/c783648d8778e5e13cf08148274fba2e to your computer and use it in GitHub Desktop.
benchmark different way to compare encoded integer in golang
package test
import (
"bytes"
"encoding/binary"
"testing"
)
var bz1, bz2 [8]byte
func init() {
binary.LittleEndian.PutUint64(bz1[:], 10000000000)
binary.LittleEndian.PutUint64(bz2[:], 90000000000)
}
func BenchmarkBytesCompare(b *testing.B) {
var result bool
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
result = bytes.Compare(bz1[:], bz2[:]) == -1
}
_ = result
}
func BenchmarkIntCompare(b *testing.B) {
var result bool
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
result = binary.LittleEndian.Uint64(bz1[:]) < binary.LittleEndian.Uint64(bz2[:])
}
_ = result
}
$ go test -run=^$ -bench=. -benchmem ./bench_test.go -count=10
goos: darwin
goarch: amd64
cpu: Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
BenchmarkBytesCompare-12 405647505 2.953 ns/op 0 B/op 0 allocs/op
BenchmarkBytesCompare-12 401131813 3.067 ns/op 0 B/op 0 allocs/op
BenchmarkBytesCompare-12 403421892 2.901 ns/op 0 B/op 0 allocs/op
BenchmarkBytesCompare-12 412267639 2.831 ns/op 0 B/op 0 allocs/op
BenchmarkBytesCompare-12 401907520 2.838 ns/op 0 B/op 0 allocs/op
BenchmarkBytesCompare-12 404371197 2.887 ns/op 0 B/op 0 allocs/op
BenchmarkBytesCompare-12 416122317 2.847 ns/op 0 B/op 0 allocs/op
BenchmarkBytesCompare-12 411978972 2.824 ns/op 0 B/op 0 allocs/op
BenchmarkBytesCompare-12 416628940 2.836 ns/op 0 B/op 0 allocs/op
BenchmarkBytesCompare-12 416411857 2.817 ns/op 0 B/op 0 allocs/op
BenchmarkIntCompare-12 1000000000 0.2500 ns/op 0 B/op 0 allocs/op
BenchmarkIntCompare-12 1000000000 0.2480 ns/op 0 B/op 0 allocs/op
BenchmarkIntCompare-12 1000000000 0.2397 ns/op 0 B/op 0 allocs/op
BenchmarkIntCompare-12 1000000000 0.2391 ns/op 0 B/op 0 allocs/op
BenchmarkIntCompare-12 1000000000 0.2388 ns/op 0 B/op 0 allocs/op
BenchmarkIntCompare-12 1000000000 0.2414 ns/op 0 B/op 0 allocs/op
BenchmarkIntCompare-12 1000000000 0.2385 ns/op 0 B/op 0 allocs/op
BenchmarkIntCompare-12 1000000000 0.2400 ns/op 0 B/op 0 allocs/op
BenchmarkIntCompare-12 1000000000 0.2407 ns/op 0 B/op 0 allocs/op
BenchmarkIntCompare-12 1000000000 0.2409 ns/op 0 B/op 0 allocs/op
PASS
ok command-line-arguments 18.404s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment