go 字符串拼接性能比较

比较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

性能

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


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

你可能感兴趣的:(go 字符串拼接性能比较)