比較fmt.Sprintf strings.Join + 重復(fù)申明bytes.Buffer 一次申明bytes.Buffer
package main
import (
"testing"
"strings"
"bytes"
"fmt"
)
var (
s = "我的加載中國(guó)號(hào)多少空間哈市的付款計(jì)劃的時(shí)間恢復(fù)健咖啡哈市的飯卡號(hào)發(fā)空間按多少宇航員"
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+"]"
}
}
//每次申明一個(gè)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 //每次申明一個(gè)buffer
BenchmarkBFN-8 10000000 164 ns/op 144 B/op 1 allocs/op //只聲明一次buffer,每次重置
PASS
結(jié)論:如果字符串少的情況下狐史,綜合耗時(shí)罢低,使用內(nèi)存,對(duì)象分配媳禁,操作便利性方面眠副,+更勝一籌