Closed thinkeridea closed 4 years ago
由该方法拓展出 exutf8.RuneSub
和 exutf8.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.RuneSub
和 exutf8.RuneSubString
函数,没有直接使用 exutf8.RuneIndexInString
效率高,但是实际差距并不大,且封装后提供更加灵活的截取字符串方案。
使用
utf8.DecodeRuneInString
逐个解析字符,使得比把字符串转为[]rune
运行效率更高,但是这并不是最好的解决方案,我需要一个方法在字符串中计算指定数量字符的索引位置,使得可以高效的利用字符串切片获得高效处理多字节字符的方案。灵感来自 #5