golang make预先分配空间

使用make给slice初始化时,不建议在一开始就分配很大空间,除非特别清楚slice的变化过程。

比如如下代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package main

import (
"fmt"
)

func main() {
s := make([]byte, 0, 32)
println(s)
s1 := append(s, 'a')
println(s1)
s2 := append(s, 'b')
println(s2)

fmt.Println(string(s1), string(s2))
}

代码输出:

[0/32]0xc000072f30
[1/32]0xc000072f30
[1/32]0xc000072f30
b b

s、s1、s2都是相同地址。出现这种情况的原因是 append 函数,在 cap 还能容纳元素的情况下,append 仅仅使用copy将元素复制到slice,不会重新申请空间:

The append built-in function appends elements to the end of a slice. If it has sufficient capacity, the destination is resliced to accommodate the new elements. If it does not, a new underlying array will be allocated.