英文:
How the slice is enlarged by append? Is the capacity always doubled?
问题
当使用append
添加一个切片时,如果需要,切片的大小可能会被扩大。因为规范没有具体指定算法,所以我很好奇。
我试图在Go源代码中找到append
的实现,但找不到。
有人可以解释一下扩大切片的具体算法吗?容量是否总是加倍?或者有人可以提供append
的源代码位置吗?我可以自己查看。
英文:
When append
a slice, the slice may be enlarged if necessary. Because the spec doesn't specify the algorithm, I am curious about it.
I try to find the append
implementation in the Go source code, but can't find it.
Could anyone explain the specified algorithm for enlarging slice? Is the capacity always doubled? or Could anyone provide the source code position of append
? I can check it myself.
答案1
得分: 27
截至2014-2020年,实施的规则如下:
- 如果向切片追加的元素数量超过当前长度的两倍以上,新的容量将设置为新的长度。
- 否则,如果当前长度小于1024,则将容量加倍;如果当前长度大于等于1024,则将容量增加25%。重复此步骤,直到新的容量适合所需的长度。
据推测,这可能不是规范的一部分,因此如果需要,启发式规则可以在将来更改。您可以在master分支上检查此实现的最新版本。
英文:
The code responsible for growing slices in append
can be found here.
As of 2014-2020 the implemented rules are:
- If appending to the slice will increase its length by more than double, the new capacity is set to the new length.
- Otherwise, double the capacity if the current length is less than 1024, or by 25% if it is larger. Repeat this step until the new capacity fits the desired length.
Presumably this isn't part of the specification so the heuristics can be changed in future if needed. You can check the most current version of this implementation on the master branch.
答案2
得分: 5
在Go 1.18中有所改变。
https://github.com/golang/go/commit/2dda92ff6f9f07eeb110ecbf0fc2d7a0ddd27f9d
初始容量 增长因子
256 2.0
512 1.63
1024 1.44
2048 1.35
4096 1.30
英文:
In Go 1.18 it changed.
https://github.com/golang/go/commit/2dda92ff6f9f07eeb110ecbf0fc2d7a0ddd27f9d
starting cap growth factor
256 2.0
512 1.63
1024 1.44
2048 1.35
4096 1.30
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论