1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package main

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

// 大量字符串拼接性能测试

// fmt.Printf
func BenchmarkFmtSprintfMore(b *testing.B) {
	var s string
	for i := 0; i < b.N; i++ {
		s += fmt.Sprintf("%s%s", "hello", "world")
	}
	fmt.Errorf(s)
}

// 加号 拼接
func BenchmarkAddMore(b *testing.B) {
	var s string
	for i := 0; i < b.N; i++ {
		s += "hello" + "world"
	}
	fmt.Errorf(s)
}

// strings.Join
func BenchmarkStringsJoinMore(b *testing.B) {
	var s string
	for i := 0; i < b.N; i++ {
		s += strings.Join([]string{"hello", "world"}, "")
	}
	fmt.Errorf(s)
}

// bytes.Buffer
func BenchmarkBufferMore(b *testing.B) {
	buffer := bytes.Buffer{}
	for i := 0; i < b.N; i++ {
		buffer.WriteString("hello")
		buffer.WriteString("world")
	}
	fmt.Errorf(buffer.String())
}

// 单次字符串拼接性能测试

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

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

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

func BenchmarkBuffer(b *testing.B) {
	for i := 0; i < b.N; i++ {
		b := bytes.Buffer{}
		b.WriteString("hello")
		b.WriteString("world")
		fmt.Errorf(b.String())
	}
}

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
$ go test -bench="."
goos: darwin
goarch: amd64
pkg: github.com/congim/testCode
cpu: Intel(R) Core(TM) i5-8257U CPU @ 1.40GHz
BenchmarkFmtSprintfMore-8         124717             66195 ns/op
BenchmarkAddMore-8                200688            101945 ns/op
BenchmarkStringsJoinMore-8        207854            104328 ns/op
BenchmarkBufferMore-8           28937617                59.37 ns/op
BenchmarkFmtSprintf-8            6131094               191.7 ns/op
BenchmarkAdd-8                  13491847                89.77 ns/op
BenchmarkStringsJoin-8           9086439               137.9 ns/op
BenchmarkBuffer-8                8177436               158.0 ns/op
PASS
ok      github.com/congim/testCode      59.921s
  • 从上可以看出单次调用字符串拼接性能 + > strings.Join > bytes.Buffer > fmt.Sprintf

  • 如果涉及到大量数据拼接推荐 bytes.buffer{}

    不晓得是我测试方式是否有问题,很多人测试结果是strings.Join最强, bytes.Buffer随后。然后各种分析内部内存分配次数!总之在适当的场景选择适当的方式吧,上线之前尽量去实际的压一次选择合适自身场景的方法~