Skip to content

Instantly share code, notes, and snippets.

@siddontang
Created July 17, 2018 14:54
Show Gist options
  • Save siddontang/576b25ecdbc454a7339994a7ec7ac0d8 to your computer and use it in GitHub Desktop.
Save siddontang/576b25ecdbc454a7339994a7ec7ac0d8 to your computer and use it in GitHub Desktop.
package prefix_access
import (
"bytes"
"encoding/binary"
"testing"
)
func hasPrefix(buf []byte, prefix []byte) bool {
return buf[0] == prefix[0] && buf[1] == prefix[1]
}
func hasPrefix2(buf []byte, prefix uint16) bool {
return binary.BigEndian.Uint16(buf) == prefix
}
func BenchmarkAccess(b *testing.B) {
prefix := []byte("tr")
buf := []byte("trabc")
b.ResetTimer()
for i := 0; i < b.N; i++ {
hasPrefix(buf, prefix)
}
}
func BenchmarkAccess2(b *testing.B) {
prefix := binary.BigEndian.Uint16([]byte("tr"))
buf := []byte("trabc")
b.ResetTimer()
for i := 0; i < b.N; i++ {
hasPrefix2(buf, prefix)
}
}
func BenchmarkHasPrefix(b *testing.B) {
prefix := []byte("tr")
b.ResetTimer()
buf := []byte("trabc")
for i := 0; i < b.N; i++ {
bytes.HasPrefix(buf, prefix)
}
}
goos: darwin
goarch: amd64
BenchmarkAccess-4 2000000000 0.81 ns/op
BenchmarkAccess2-4 2000000000 0.27 ns/op
BenchmarkHasPrefix-4 300000000 5.66 ns/op
goos: linux
goarch: amd64
BenchmarkAccess-40 2000000000 0.97 ns/op
BenchmarkAccess2-40 2000000000 0.33 ns/op
BenchmarkHasPrefix-40 200000000 7.34 ns/op
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment