If you are comfortable enough with the fact that this might break on a later release (although doubtful), you can use unsafe :
func unsafeCompare(a string, b []byte) int { abp := *(*[]byte)(unsafe.Pointer(&a)) return bytes.Compare(abp, b) } func unsafeEqual(a string, b []byte) bool { bbp := *(*string)(unsafe.Pointer(&b)) return a == bbp }
playground
Benchmarks :
// using: // aaa = strings.Repeat("a", 100) // bbb = []byte(strings.Repeat("a", 99) + "b") // go 1.5 BenchmarkCopy-8 20000000 75.4 ns/op BenchmarkPetersEqual-8 20000000 83.1 ns/op BenchmarkUnsafe-8 100000000 12.2 ns/op BenchmarkUnsafeEqual-8 200000000 8.94 ns/op // go 1.4 BenchmarkCopy 10000000 233 ns/op BenchmarkPetersEqual 20000000 72.3 ns/op BenchmarkUnsafe 100000000 15.5 ns/op BenchmarkUnsafeEqual 100000000 10.7 ns/op
source share