thinkeridea / go-extend

go语言扩展包,收集一些常用的操作函数,辅助更快的完成开发工作,并减少重复代码
https://pkg.go.dev/github.com/thinkeridea/go-extend
MIT License
1.34k stars 158 forks source link

扩展 utf8 提供根据字符数量确定字符串索引位置 #7

Closed thinkeridea closed 4 years ago

thinkeridea commented 4 years ago

使用 utf8.DecodeRuneInString 逐个解析字符,使得比把字符串转为 []rune 运行效率更高,但是这并不是最好的解决方案,我需要一个方法在字符串中计算指定数量字符的索引位置,使得可以高效的利用字符串切片获得高效处理多字节字符的方案。

灵感来自 #5

thinkeridea commented 4 years ago

由该方法拓展出 exutf8.RuneSubexutf8.RuneSubString 方法,其截取字符串效率大幅度提升,详细的测试在 exunicode/exutf8/benchmark/sub_string_test.go 中,以下是我测试的效果:

go test -benchmem -bench="."                                                        
goos: darwin
goarch: amd64
pkg: github.com/thinkeridea/go-extend/exunicode/exutf8/benchmark
BenchmarkSubStrRunes-8                    875361              1511 ns/op             336 B/op          2 allocs/op
BenchmarkSubStrRange-8                  11738449                96.7 ns/op             0 B/op          0 allocs/op
BenchmarkSubStrDecodeRuneInString-8     11425912               111 ns/op               0 B/op          0 allocs/op
BenchmarkSubStrRuneIndexInString-8      14508450                82.0 ns/op             0 B/op          0 allocs/op
BenchmarkSubStrRuneSubString-8          14334190                82.3 ns/op             0 B/op          0 allocs/op
PASS
ok      github.com/thinkeridea/go-extend/exunicode/exutf8/benchmark     7.447s

封装后的 exutf8.RuneSubexutf8.RuneSubString 函数,没有直接使用 exutf8.RuneIndexInString 效率高,但是实际差距并不大,且封装后提供更加灵活的截取字符串方案。