golang make预先分配空间
使用make给slice初始化时,不建议在一开始就分配很大空间,除非特别清楚slice的变化过程。
比如如下代码:
1 | package main |
代码输出:
[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.