我是 Go 新手,正在阅读 O'reilly 出版的一本名为“学习 Go”的书。在阅读有关切片的内容时,有以下声明:
为了增加切片的大小,从 Go 1.14 开始,规则是将容量加倍,直到达到 1024 的大小,然后再增长 25%。”
我写了这段 Go 代码来证明这一点。
package main
import "fmt"
func main() {
var length uint16 = 1024
var x []int
for i := 0; i < int(length); i++ {
x = append(x, i)
fmt.Printf("\nLength is %d. Capacity is %d", len(x), cap(x))
}
}
Run Code Online (Sandbox Code Playgroud)
从 0 到 len(x)==512 事实证明,Go 运行时使容量(也称为大小)翻倍。但对我来说有趣的部分开始了:当 len(x) >= 512 时,我预计容量为 1024,因为 512*2 = 1024。然而结果如下:
Length is 513. Capacity is 848
Run Code Online (Sandbox Code Playgroud)
所以大约增加了 65%。谁可以给我解释一下这个?
roc*_*a2q 16
从 Go 1.14 开始
Go 1.20 刚刚发布(2023-02-01 发布)。Go 1.21 的工作已经开始。阅读 Go 源代码,了解自 Go 1.14(2020-02-25 发布)以来的变化。
例如,
去/src/runtime/slice.go:
// Transition from growing 2x for small slices
// to growing 1.25x for large slices. This formula
// gives a smooth-ish transition between the two.
Run Code Online (Sandbox Code Playgroud)
运行时:使切片增长公式更平滑 (2021 年 9 月 27 日星期一 20:53:51 提交):
Instead of growing 2x for < 1024 elements and 1.25x for >= 1024 elements,
use a somewhat smoother formula for the growth factor. Start reducing
the growth factor after 256 elements, but slowly.
starting cap growth factor
256 2.0
512 1.63
1024 1.44
2048 1.35
4096 1.30
(Note that the real growth factor, both before and now, is somewhat
larger because we round up to the next size class.)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
992 次 |
| 最近记录: |