go 字符串拼接性能比较

2018-07-10  本文已影响0人  xiaomeng79

比较fmt.Sprintf strings.Join + 重复申明bytes.Buffer 一次申明bytes.Buffer

package main

import (
    "testing"
    "strings"
    "bytes"
    "fmt"
)

var (
    s = "我的加载中国号多少空间哈市的付款计划的时间恢复健咖啡哈市的饭卡号发空间按多少宇航员"
    sub = "宇航员"
    //s = "abcdrfghidhsdh2jkhsdkjfs"
    //sub = "2j"
    _s = []string{s,"[",sub,"]"}
    buf = bytes.Buffer{}
)

//fmt.Sprintf
func BenchmarkS(b *testing.B) {
    b.ReportAllocs()
    for i:=0;i<b.N;i++ {
        fmt.Sprintf("%s[%s]",s,sub)
    }
}

//strings.Join
func BenchmarkJ(b *testing.B) {
    b.ReportAllocs()
    for i:=0;i<b.N;i++ {
        strings.Join(_s,"")
    }
}

//+
func BenchmarkSJ(b *testing.B) {
    b.ReportAllocs()
    for i:=0;i<b.N;i++ {
        _ =s + "[" + sub+"]"
    }
}

//每次申明一个buffer
func BenchmarkBF(b *testing.B) {
    b.ReportAllocs()
    for i:=0;i<b.N;i++ {
        b := bytes.Buffer{}
        b.WriteString(s)
        b.WriteString("[")
        b.WriteString(sub)
        b.WriteString("]")
        b.String()
    }
}

//只声明一次,每次重置
func BenchmarkBFN(b *testing.B) {
    b.ReportAllocs()
    for i:=0;i<b.N;i++ {
        buf.Reset()
        buf.WriteString(s)
        buf.WriteString("[")
        buf.WriteString(sub)
        buf.WriteString("]")
        buf.String()
    }
}

性能

goos: linux
goarch: amd64
BenchmarkS-8        5000000      368 ns/op    176 B/op     3 allocs/op  //fmt.Sprintf
BenchmarkJ-8        5000000      250 ns/op    288 B/op     2 allocs/op  //strings.Join
BenchmarkSJ-8      10000000      152 ns/op    144 B/op     1 allocs/op  //+
BenchmarkBF-8       2000000      707 ns/op    640 B/op     4 allocs/op  //每次申明一个buffer
BenchmarkBFN-8     10000000      164 ns/op    144 B/op     1 allocs/op  //只声明一次buffer,每次重置
PASS


结论:如果字符串少的情况下,综合耗时,使用内存,对象分配,操作便利性方面,+更胜一筹

上一篇下一篇

猜你喜欢

热点阅读