Skip to content

Instantly share code, notes, and snippets.

@totoleo
Last active June 19, 2020 11:41
Show Gist options
  • Save totoleo/d2ffda451127e31a0beedd38229356b4 to your computer and use it in GitHub Desktop.
Save totoleo/d2ffda451127e31a0beedd38229356b4 to your computer and use it in GitHub Desktop.
split 与 index 的性能对比
BenchmarkSubStr/split
BenchmarkSubStr/split-4 11353098 106 ns/op 32 B/op 1 allocs/op
BenchmarkSubStr/index
BenchmarkSubStr/index-4 187964112 6.37 ns/op 0 B/op 0 allocs/op
package perf
import (
"strings"
"testing"
)
func TestSubStr(t *testing.T) {
t.Run("splitAndGet", func(t *testing.T) {
})
}
func BenchmarkSubStr(b *testing.B) {
str := "hello.world"
split := func(str string) (string, string, bool) {
parts := strings.Split(str, ".")
if len(parts) == 1 {
return str, "", false
}
return parts[0], parts[1], true
}
index := func(str string) (string, string, bool) {
pos := strings.IndexByte(str, '.')
if pos < 0 || pos == len(str)-1 {
return str, "", false
}
a := str[0:pos]
b := str[pos+1:]
return a, b, true
}
b.Run("split", func(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
split(str)
}
})
b.Run("index", func(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
_,_,ok:=index(str)
if ok{
}
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment