学习 go 语言【8】strings.Builder vs bytes.Buffer

结论

  • strings.Builder:省内存
  • bytes.Buffer:快

代码

性能测试程序如下:

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
package benchmark_test

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

var (
ss = "1234567890abcdefghijklmnopqrstuvwxyz"
bs = []byte(ss)
rn = 'a'
bt = byte('a')
)

func BenchmarkBuilderWrite(b *testing.B) {
var builder strings.Builder
for i := 0; i < b.N; i++ {
builder.Write(bs)
}
}

func BenchmarkBuiderWriteByte(b *testing.B) {
var builder strings.Builder
for i := 0; i < b.N; i++ {
builder.WriteByte(bt)
}
}

func BenchmarkBuilderWriteRune(b *testing.B) {
var builder strings.Builder
for i := 0; i < b.N; i++ {
builder.WriteRune(rn)
}
}

func BenchmarkBuilderWriteString(b *testing.B) {
var builder strings.Builder
for i := 0; i < b.N; i++ {
builder.WriteString(ss)
}
}

func BenchmarkBufferWrite(b *testing.B) {
var buffer bytes.Buffer
for i := 0; i < b.N; i++ {
buffer.Write(bs)
}
}

func BenchmarkBufferWriteByte(b *testing.B) {
var buffer bytes.Buffer
for i := 0; i < b.N; i++ {
buffer.WriteByte(bt)
}
}

func BenchmarkBufferWriteRune(b *testing.B) {
var buffer bytes.Buffer
for i := 0; i < b.N; i++ {
buffer.WriteRune(rn)
}
}

func BenchmarkBufferWriteString(b *testing.B) {
var buffer bytes.Buffer
for i := 0; i < b.N; i++ {
buffer.WriteString(ss)
}
}
如果您使用微信,也可以关注公众号 UMU618,在公众号文章里评论。