为什么Go中的append()函数会使数组上限加倍?

时间:2019-07-24 12:14:10

标签: go

在长度等于其容量的数组中,内置函数append()将数组加倍,而不是通过组合原始数组的长度和要附加的项来对其进行扩展。

示例:

func main() {
  a := []int{0, 1, 2, 3}
  fmt.Printf("Array: %v\tcapacity: %d\n", a, cap(a))
  a = append(a, 4)
  fmt.Printf("Array: %v\tcapacity: %d\n", a, cap(a))
}

结果:

Array: [0 1 2 3]    capacity: 4
Array: [0 1 2 3 4]  capacity: 8

当我尝试搜索它时,我只找到了append()使用的growslice()函数的源代码

newcap := old.cap
doublecap := newcap + newcap
if cap > doublecap {
    newcap = cap
} else {
    if old.len < 1024 {
        newcap = doublecap
    } else {
        // Check 0 < newcap to detect overflow
        // and prevent an infinite loop.
        for 0 < newcap && newcap < cap {
            newcap += newcap / 4
        }
        // Set newcap to the requested cap when
        // the newcap calculation overflowed.
        if newcap <= 0 {
            newcap = cap
        }
    }
}

显然,它的完全意图是,如果需要增加切片帽,那么如果切片len小于1024,则将其加倍,否则将增加.25

我的问题是-为什么会这样?这种行为背后的想法是什么?

编辑:链接没有回答我的问题,它只是说明数组已加倍的事实。链接的问题是“这样有效吗?” -是的我的问题是“ 为什么如此工作?”

0 个答案:

没有答案