字符串替换NewReplacer竟然干不过Replace多次替换方式

编写代码时,字符串替换操作是常有的事情,Go 语言中也为我们内置了强大的字符串替换方法,总共是涉及到三个函数:

<code>Replace(s, old, new string, n int)
ReplaceAll(s, old, new string)
NewReplacer(oldnew ...string)/<code>

Replace() 函数可以使用第四个参数 n 来控制从匹配的字符串中允许最多替换的个数(顺序是从左至右),如果 n < 0 那么其实就等价于 ReplaceAll() 函数,ReplaceAll() 内部实现其实就是 n = -1 时的 Replace() 函数,不妨看看如下源代码:

字符串替换NewReplacer竟然干不过Replace多次替换方式

因此,不要被名字所误解,其实 Replace() 也能实现全局的文本替换工作。请看如下:

只替换第一个 Cat

字符串替换NewReplacer竟然干不过Replace多次替换方式

打印结果:

<code>Dog NewCat Mouse Duck Cat, the Cat is gray/<code>

替换所有 Cat

字符串替换NewReplacer竟然干不过Replace多次替换方式

打印结果:

<code>Dog NewCat Mouse Duck NewCat, the NewCat is gray/<code>

请记住一点:n 代表的是替换多少个,而不是从第几个开始替换!

替换多个值

Replace() 和 ReplaceAll() 函数有个比较尴尬的地方,不能实现同时替换多个值。如上实例中,如果我们希望同时替换文本中的 Dog 和 Cat 时,这里函数就有点力不从心了,所以就有了 strings.NewReplacer() 函数

strings.NewReplacer() 函数允许我们批量替换多个不同的字符串,但该函数参数要求必须是成对的,第一个参数为需要替换的值,第二参数为替换后的值,第三,第四个,一次类推,两两为一组,如下实例,我们将 Dog 和 Cat 同时替换为新值:

字符串替换NewReplacer竟然干不过Replace多次替换方式

打印结果:

<code>NewDog NewCat Mouse Duck NewCat, the NewCat is gray/<code>

疑问?

批量替换多个值,使用 NewReplacer() 函数 还是使用 ReplaceAll() 或 Replace() 替换多次,谁的性能更好呢?我们不妨来做一个验证:

字符串替换NewReplacer竟然干不过Replace多次替换方式

这里我们编写了三个 Benchmark

函数,BenchmarkReplacer() 测试 Replacer() 函数效果,BenchmarkReplace() 和 BenchmarkReplaceAll() 函数分别代表 Replace 和 ReplaceAll, 测试结果如下,可能令你意想不到:

<code>goos: darwin
goarch: amd64
pkg: github.com/apptut/go-labs/strings
BenchmarkReplacer-4 1000000000 0.0161 ns/op
BenchmarkReplaceAll-4 1000000000 0.00249 ns/op
BenchmarkReplace-4 1000000000 0.00269 ns/op/<code>

从结果上来说,竟然 Replace() 和 ReplaceAll() 多次替换方式竟然比 NewReplacer()函数要好7倍左右,这个结论有点让人大跌眼镜!


分享到:


相關文章: