- `+` 拼接 最慢 少量比较推荐
- `strings.join` 拼接 其次-推荐
- `buffers.NewBufferString` 拼接 最快,需要自己实现
博客原文链接:[https://www.douyacun.com/article/64bf57a2d3099acbb960ca561d225628](https://www.douyacun.com/article/64bf57a2d3099acbb960ca561d225628)
我实际测试了一下,拼接 1-10万数字
```go
func main() {
a := make([]string, 100000)
for i := 1; i <= 100000; i++ {
a = append(a, strconv.Itoa(i))
}
fmt.Println(unsafe.Sizeof(a))
// -- 预热
fmt.Println("--- 预热")
Builder(a)
buffer(a)
fmt.Println("--- 开始")
Builder(a)
buffer(a)
}
func buffer(a []string) {
start := time.Now()
var str = bytes.NewBufferString("")
for _, i := range a {
str.WriteString(i)
}
latency := time.Now().Sub(start)
fmt.Printf("buffer latency: %s len: %d\n", latency, len(str.String()))
}
func Builder(a []string) {
start := time.Now()
var str = strings.Builder{}
for _, i := range a {
str.WriteString(i)
}
latency := time.Now().Sub(start)
fmt.Printf("builder latency: %s len: %d\n", latency, len(str.String()))
}
```
第一次:
--- 预热
builder latency: 3.25557ms len: 488895
buffer latency: 4.47419ms len: 488895
--- 开始
builder latency: 6.116895ms len: 488895
buffer latency: 6.607627ms len: 488895
第二次:
--- 预热
builder latency: 3.336517ms len: 488895
buffer latency: 2.084284ms len: 488895
--- 开始
builder latency: 2.634188ms len: 488895
buffer latency: 2.930336ms len: 488895
多次测试,都是Builder快一点,@ focusonline 牛逼
#4
更多评论
1楼 <a href="/user/focusonline" title="@focusonline">@focusonline</a>
```go
type Builder struct {
addr *Builder // of receiver, to detect copies by value
buf []byte
}
```
```go
type Buffer struct {
buf []byte // contents are the bytes buf[off : len(buf)]
off int // read at &buf[off], write at &buf[len(buf)]
lastRead readOp // last read operation, so that Unread* can work correctly.
}
```
都是存储字节slice的,
- Builder writeString是append到buf中,会有扩容操作,
- Buffer writeString 是通过copy内存实现的
Buffer用起来更顺手
#2