切片如何通过追加放大?容量是否总是增加一倍? [英] How the slice is enlarged by append? Is the capacity always doubled?

查看:79
本文介绍了切片如何通过追加放大?容量是否总是增加一倍?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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.

我尝试在Go源代码中找到append实现,但是找不到它.

I try to find the append implementation in the Go source code, but can't find it.

有人可以解释扩大切片的指定算法吗?容量是否总是增加一倍?或任何人都可以提供append的源代码位置吗?我可以自己检查.

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.

推荐答案

append中负责切片生成的代码可以在此处找到.

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

截至2014-2020年,已实施的规则为:

As of 2014-2020 the implemented rules are:

  1. 如果附加到切片将使其长度增加两倍以上,则将新容量设置为新长度.
  2. 否则,如果当前长度小于1024,则将容量增加一倍;如果更大,则将容量增加25%.重复此步骤,直到新容量适合所需的长度.

大概这不是规范的一部分,因此将来可以根据需要更改试探法.您可以在

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.

这篇关于切片如何通过追加放大?容量是否总是增加一倍?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆