utils: use strings.Split instead of strings.IndexByte (#1400)

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
```
This commit is contained in:
田欧 2018-06-21 09:31:43 +08:00 committed by Bo-Yi Wu
parent caf3e350a5
commit 87d536c001
1 changed files with 1 additions and 4 deletions

View File

@ -103,10 +103,7 @@ func parseAccept(acceptHeader string) []string {
parts := strings.Split(acceptHeader, ",") parts := strings.Split(acceptHeader, ",")
out := make([]string, 0, len(parts)) out := make([]string, 0, len(parts))
for _, part := range parts { for _, part := range parts {
if index := strings.IndexByte(part, ';'); index >= 0 { if part = strings.TrimSpace(strings.Split(part, ";")[0]); part != "" {
part = part[0:index]
}
if part = strings.TrimSpace(part); part != "" {
out = append(out, part) out = append(out, part)
} }
} }