美文网首页
golang字符串连接操作性能比较

golang字符串连接操作性能比较

作者: hewolf | 来源:发表于2019-12-23 19:39 被阅读0次

方式

  • 1-使用+号连接
  • 2-使用fmt.Sprintf连接

压测用例

func BenchmarkSprintf(b *testing.B) {
    field := "f15"
    b.Run("run +", func(b *testing.B) {
        b.ResetTimer()
        b.RunParallel(func(pb *testing.PB) {
            for pb.Next() {
                ret := "'" + field + "'"
                fmt.Sprintf(ret)
            }
        })
    })
    b.Run("run sprints", func(b *testing.B) {
        b.ResetTimer()
        b.RunParallel(func(pb *testing.PB) {
            for pb.Next() {
                ret := fmt.Sprintf("'%s'", field)
                fmt.Sprintf(ret)
            }
        })
    })
}

压测结果

goos: darwin
goarch: amd64
pkg: mxdp/benchmarks
BenchmarkSprintf/run_+-8            48479692            30.4 ns/op
BenchmarkSprintf/run_sprints-8      22349860            79.8 ns/op
PASS

可以很明显看到+号的操作性能大约是格式化连接的2-3倍速度,但是格式化输出代码更容易阅读,如果单纯追求性能,使用+号输出比较好

相关文章

网友评论

      本文标题:golang字符串连接操作性能比较

      本文链接:https://www.haomeiwen.com/subject/jqdtoctx.html