关于go:golang-字符串拼接方法对比

27次阅读

共计 2247 个字符,预计需要花费 6 分钟才能阅读完成。

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

  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。

正文完
 0