【Go 字符串】如何连接字符串

Go有多种字符串拼接方式,不同方式的效率不同:

  1. 使用加号+
  2. bytes.Buffer
  3. strings.Builder 效率最佳
  4. copy()
  5. strings.Join()
  • 测试
    go test -bench=. -benchmem
    Concatenating_test.go
package main

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

func BenchmarkConcat(b *testing.B) {
    var str string
    b.ResetTimer()
    for i := 0; i < b.N; i++ {
        str += "x"
    }
    b.StopTimer()
    if s := strings.Repeat("x", b.N); str != s {
        b.Errorf("Unexpected result: got:%s want:%s", str, s)
    }
}

func BenchmarkBuffer(b *testing.B) {
    var buf bytes.Buffer
    b.ResetTimer()
    for i := 0; i < b.N; i++ {
        buf.WriteString("x")
    }
    b.StopTimer()
    if s := strings.Repeat("x", b.N); buf.String() != s {
        b.Errorf("Unexpected result: got:%s want:%s", buf.String(), s)
    }
}

func BenchmarkStringBuilder(b *testing.B) {
    var strBuilder strings.Builder
    b.ResetTimer()
    for i := 0; i < b.N; i++ {
        strBuilder.WriteString("x")
    }
    b.StopTimer()
    if s := strings.Repeat("x", b.N); strBuilder.String() != s {
        b.Errorf("Unexpected result: got:%s want:%s", strBuilder.String(), s)
    }
}

func BenchmarkCopy(b *testing.B) {
    bs := make([]byte, b.N)
    bl := 0
    b.ResetTimer()
    for i := 0; i < b.N; i++ {
        bl += copy(bs[bl:], "x")
    }
    b.StopTimer()
    if s := strings.Repeat("x", b.N); string(bs) != s {
        b.Errorf("Unexpected result: got:%s want:%s", string(bs), s)
    }
}

func BenchmarkStringJoin(b *testing.B) {
    var strSlice []string
    b.ResetTimer()
    for i := 0; i < b.N; i++ {
        strSlice = append(strSlice, "x")
    }
    b.StopTimer()
    if s, str := strings.Repeat("x", b.N), strings.Join(strSlice, ""); str != s {
        b.Errorf("Unexpected result: got:%s want:%s", str, s)
    }
}

测试结果

BenchmarkConcat-8            1000000         39347 ns/op      503994 B/op          1 allocs/op
BenchmarkBuffer-8           200000000            8.63 ns/op        2 B/op          0 allocs/op
BenchmarkStringBuilder-8    1000000000           3.29 ns/op        6 B/op          0 allocs/op
BenchmarkCopy-8             300000000            4.30 ns/op        0 B/op          0 allocs/op
BenchmarkStringJoin-8       20000000            86.6 ns/op        80 B/op          0 allocs/op
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容