Go 切片容量增加率

问题描述 投票:0回答:1

我是 Go 的新手,正在阅读 O'reilly 出版的一本名为“Learning 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))
    }
}

从 0 到 len(x)==512 事实证明,Go 运行时将容量翻倍(也就是大小)。但是这里对我来说有趣的部分开始了:当 len(x) >= 512 时,我期望容量为 1024,因为 512*2 = 1024。但是结果如下:

Length is 513. Capacity is 848

所以大约增加了 65%。有人可以给我解释一下吗?

go slice
1个回答
15
投票

从 Go 1.14 开始

Go 1.20 刚刚发布(2023-02-01 发布)。 Go 1.21 的工作已经开始。阅读 Go 源代码以查看自 Go 1.14(2020-02-25 发布)以来的变化。

例如,

go/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.

运行时:使切片增长公式更平滑一些 (承诺于 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.)
© www.soinside.com 2019 - 2024. All rights reserved.