go语言数组内存是怎么扩容的

楚天乐 2323 0 条

话不多说,上测试代码和结果

package main

import (
    "fmt"
)

func main() {
    var orderIds []int
    fmt.Println(len(orderIds), cap(orderIds))

    fmt.Println("已使用", "\t\t", "容量", "\t\t", "增量")
    var lastCap = cap(orderIds)

    for i := 0; i < 100000; i++ {   
        orderIds = append(orderIds, 1)

        if cap(orderIds) != lastCap{
            fmt.Println(len(orderIds), "\t\t", cap(orderIds), "\t\t", cap(orderIds)-lastCap)
            lastCap = cap(orderIds)
        }
    }
}

输出

0 0
已使用          容量          增量
1        2       2
3        4       2
5        8       4
9        16          8
17       32          16
33       64          32
65       128         64
129          256         128
257          512         256
513          1024        512
1025         1344        320
1345         1696        352
1697         2368        672
2369         3072        704
3073         4096        1024
4097         5120        1024
5121         6816        1696
6817         10240       3424
10241        14336       4096
14337        18432       4096
18433        24576       6144
24577        30720       6144
30721        38912       8192
38913        49152       10240
49153        61440       12288
61441        77824       16384
77825        98304       20480
98305        122880      24576

总结

  • 容量在1024以下,简单粗暴的翻倍,扩容后容量2^n, 1<=n<=10
  • 超过1024,大概看下知道就好,我也懒得去看源码总结公式了


发表我的评论
昵称 (必填)
邮箱 (必填)
网址
执行时间: 1714062901488.2 毫秒