Optimized EqualBytesStr

This commit is contained in:
Aliaksandr Valialkin
2015-11-24 12:57:01 +02:00
parent 146145240d
commit 961eef082b
2 changed files with 15 additions and 10 deletions
+3 -10
View File
@@ -297,17 +297,10 @@ func hexChar(c byte) byte {
// EqualBytesStr returns true if string(b) == s.
//
// It doesn't allocate memory unlike string(b) do.
// This function has no performance benefits comparing to string(b) == s.
// It is left here for backwards compatilbility only.
func EqualBytesStr(b []byte, s string) bool {
if len(s) != len(b) {
return false
}
for i, n := 0, len(s); i < n; i++ {
if s[i] != b[i] {
return false
}
}
return true
return string(b) == s
}
// AppendBytesStr appends src to dst and returns dst
+12
View File
@@ -36,3 +36,15 @@ func BenchmarkLowercaseBytesMixed(b *testing.B) {
}
})
}
func BenchmarkEqualBytesStr(b *testing.B) {
s := "foobarbaraz"
bs := []byte(s)
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
if !EqualBytesStr(bs, s) {
b.Fatalf("unexpected result: %q != %q", bs, s)
}
}
})
}