From 87d536c00120e6631cd7e6ff100739858e07e002 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=94=B0=E6=AC=A7?= Date: Thu, 21 Jun 2018 09:31:43 +0800 Subject: [PATCH] utils: use strings.Split instead of strings.IndexByte (#1400) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit And I test them benchmark: code: ```go # stringsbench.go package stringsbench import "strings" func index(part string) string { if index := strings.IndexByte(part, ';'); index >= 0 { if part := strings.TrimSpace(strings.Split(part, ";")[0]); part != "" { return part[0:index] } } return "" } func split(part string) string { return strings.Split(part, ";")[0] } ``` ```go # stringsbench_test.go package stringsbench import ( "testing" ) func BenchmarkIndex(b *testing.B) { b.RunParallel(func(pb *testing.PB) { for pb.Next() { index("text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8") } }) } func BenchmarkSplit(b *testing.B) { b.RunParallel(func(pb *testing.PB) { for pb.Next() { split("text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8") } }) } ``` And the result: ```shell ➜ strings go test --bench=. goos: darwin goarch: amd64 BenchmarkIndex-8 30000000 46.1 ns/op BenchmarkSplit-8 50000000 35.9 ns/op PASS ok _/Users/tianou/strings 3.271s ➜ strings go test --bench=. goos: darwin goarch: amd64 BenchmarkIndex-8 30000000 44.2 ns/op BenchmarkSplit-8 50000000 34.7 ns/op PASS ok _/Users/tianou/strings 3.156s ➜ strings go test --bench=. goos: darwin goarch: amd64 BenchmarkIndex-8 30000000 45.6 ns/op BenchmarkSplit-8 50000000 35.3 ns/op PASS ok _/Users/tianou/strings 3.230s ``` --- utils.go | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/utils.go b/utils.go index 278029d7..bf32c775 100644 --- a/utils.go +++ b/utils.go @@ -103,10 +103,7 @@ func parseAccept(acceptHeader string) []string { parts := strings.Split(acceptHeader, ",") out := make([]string, 0, len(parts)) for _, part := range parts { - if index := strings.IndexByte(part, ';'); index >= 0 { - part = part[0:index] - } - if part = strings.TrimSpace(part); part != "" { + if part = strings.TrimSpace(strings.Split(part, ";")[0]); part != "" { out = append(out, part) } }