字符串拼接有以下几种方法:

  1. 加号+
  2. fmt.Sprintf
  3. strings.Join
  4. bytes.Buffer
  5. strings.Builder 此方法为官方推荐

新建单元测试文件string_test.go

package test

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

func BenchmarkFmtSprintf(b *testing.B) {
    for i := 0; i < b.N; i++ {
        s := fmt.Sprintf("%s%s", "abcdefghijklmnopqrstuvwxyz", "123456789")
        fmt.Errorf(s)
    }

}

func BenchmarkAdd(b *testing.B) {
    for i := 0; i < b.N; i++ {
        s := "abcdefghijklmnopqrstuvwxyz" +"123456789"
        fmt.Errorf(s)
    }
}
func BenchmarkStringsJoin(b *testing.B) {
    for i := 0; i < b.N; i++ {
        s := strings.Join([]string{"abcdefghijklmnopqrstuvwxyz","123456789"}, "")
        fmt.Errorf(s)
    }
}
func BenchmarkBuffer(b *testing.B) {

    for i := 0; i < b.N; i++ {
        buf := bytes.Buffer{}
        buf.WriteString("abcdefghijklmnopqrstuvwxyz")
        buf.WriteString("123456789")
        fmt.Errorf(buf.String())
    }
}
func BenchmarkBuilder(b *testing.B) {
    for i := 0; i < b.N; i++ {
        builder := strings.Builder{}
        builder.WriteString("abcdefghijklmnopqrstuvwxyz")
        builder.WriteString("123456789")
        fmt.Errorf(builder.String())
    }
}

执行 go test string_test.go -benchmem -bench=".*"
结果:
BenchmarkFmtSprintf-4 2962962 400.6 ns/op 112 B/op 3 allocs/op
BenchmarkAdd-4 6629833 207.7 ns/op 64 B/op 2 allocs/op
BenchmarkStringsJoin-4 4255318 291.6 ns/op 112 B/op 3 allocs/op
BenchmarkBuffer-4 2948402 368.3 ns/op 176 B/op 4 allocs/op
BenchmarkBuilder-4 3149605 352.1 ns/op 160 B/op 4 allocs/op
PASS
ok command-line-arguments 8.219s
执行效率排序+>join>fmt.Sprintf>strings.Builder>bytes.Buffer

新建单元测试文件string2_test.go

package test

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

func BenchmarkAdd2(b *testing.B) {
    s:= "abcdefghijklmnopqrstuvwxyz"
    for i := 0; i < b.N; i++ {
        s += "abcdefghijklmnopqrstuvwxyz"
    }
    fmt.Errorf(s)
}

func BenchmarkBuffer2(b *testing.B) {
    buf := bytes.Buffer{}
    for i := 0; i < b.N; i++ {
        buf.WriteString("abcdefghijklmnopqrstuvwxyz")
    }
    fmt.Errorf(buf.String())
}
func BenchmarkBuilder2(b *testing.B) {
    builder := strings.Builder{}
    for i := 0; i < b.N; i++ {
        builder.WriteString("abcdefghijklmnopqrstuvwxyz")
    }
    fmt.Errorf(builder.String())
}

执行 go test string2_test.go -benchmem -bench=".*"
结果:

goos: windows
goarch: amd64
cpu: Intel(R) Core(TM) i7-6500U CPU @ 2.50GHz
BenchmarkAdd2-4 10000 101400 ns/op 133806 B/op 1 allocs/op
BenchmarkBuffer2-4 15974260 79.25 ns/op 145 B/op 0 allocs/op
BenchmarkBuilder2-4 17142856 59.38 ns/op 189 B/op 0 allocs/op
PASS
ok command-line-arguments 4.912s
执行效率排序:strings.Builder>bytes.Buffer>加号
且strings.Builder和bytes.Buffer分配内存大小和次数,要比加号效率更好

总结:

由此可知在不同的使用场景,应使用不同的拼接方法,在一些简单的拼接字符串里使用加号简单高效,在复杂的拼接场景推荐strings.Builder和bytes.Buffer。


guyan0319
1.5k 声望721 粉丝

坚持但不盲目