通过`append`方法如何扩大切片的大小?容量是否总是翻倍增加?

huangapple go评论70阅读模式
英文:

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

在这里可以找到负责在append中增长切片的代码。

截至2014-2020年,实施的规则如下:

  1. 如果向切片追加的元素数量超过当前长度的两倍以上,新的容量将设置为新的长度。
  2. 否则,如果当前长度小于1024,则将容量加倍;如果当前长度大于等于1024,则将容量增加25%。重复此步骤,直到新的容量适合所需的长度。

据推测,这可能不是规范的一部分,因此如果需要,启发式规则可以在将来更改。您可以在master分支上检查此实现的最新版本。

英文:

The code responsible for growing slices in append can be found here.

As of 2014-2020 the implemented rules are:

  1. If appending to the slice will increase its length by more than double, the new capacity is set to the new length.
  2. 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

huangapple
  • 本文由 发表于 2014年5月8日 10:28:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/23531737.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定