1、使用 rune
func BenchmarkSubstr1(b *testing.B) {
s := "bench基准测试,1212"
for i := 0; i < b.N; i++ {
s1 := []rune(s)
s2 := s1[1:6]
_ = string(s2)
}
}
2、使用 utf 包
utf8.DecodeRuneInString()
func DecodeRuneInString(s string) (r rune, size int)
返回一个 rune 类型,以及此字符占用几个字节。
func BenchmarkSubstr2(b *testing.B) {
s := "bench基准测试,1212"
st := 1
en := 6
for i := 0; i < b.N; i++ {
var start, end int
var c int
for i := 0; i <= en && c < len(s); i++ {
_, size := utf8.DecodeRuneInString(s[c:])
if i == st {
start = c
}
if i == en {
end = c
}
c += size
}
_ = s[start:end]
}
}
3、使用 range 遍历
range字符ASCII中文字符
func TestSubstr(t *testing.T) {
s := "bench基准测试,1212"
for k, v := range s {
fmt.Println(k, string(v))
}
}
打印输出
0 b
1 e
2 n
3 c
4 h
5 基
8 准
11 测
14 试
17 ,
20 1
21 2
22 1
23 2
可见 range 默认就支持 unicode,因此变量 k 不是连续的,找到 k 即可。
func TestSubstr(t *testing.T) {
s := "bench基准测试,1212"
var start, end int
var c int
for k := range s {
if c == 1 {
start = k
}
if c == 6 {
end = k
}
c++
}
fmt.Println(s[start:end]) // ench基
}
func BenchmarkSubstr3(b *testing.B) {
s := "bench基准测试,1212"
for i := 0; i < b.N; i++ {
var start, end int
var c int
for k := range s {
if c == 1 {
start = k
}
if c == 6 {
end = k
}
c++
}
_ = s[start:end]
}
}
> go test -bench=BenchmarkSubstr -benchtime=100000x -benchmem
goos: windows
goarch: amd64
pkg: test
cpu: Intel(R) Core(TM) i7-4790 CPU @ 3.60GHz
BenchmarkSubstr1-8 100000 107.5 ns/op 0 B/op 0 allocs/op
BenchmarkSubstr2-8 100000 37.74 ns/op 0 B/op 0 allocs/op
BenchmarkSubstr3-8 100000 37.72 ns/op 0 B/op 0 allocs/op