Go capacity of slice when append

In go-tour the offcial guide, the append make the capacity

package main

import "fmt"

func main() {
	a := make([]int,0)
	printSlice("a", a)

	// append works on nil slices.
	a = append(a, 0)
	printSlice("a", a)

	// the slice grows as needed.
	a = append(a, 1)
	printSlice("a", a)

	// we can add more than one element at a time.
	a = append(a, 2, 3, 4)
	printSlice("a", a)
}

func printSlice(s string, x []int) {
	fmt.Printf("%s len=%d cap=%d %v\n",
		s, len(x), cap(x), x)
}

finally came out the capacity can be 6 and 8 some times, so check what happened behind the append.

below implement the append.

https://github.com/golang/go/blob/5476967b1a3d29fef4061999c00cadbec19ac0e3/src/cmd/compile/internal/gc/walk.go#L2901


below implements the capcity


https://github.com/golang/go/blob/5476967b1a3d29fef4061999c00cadbec19ac0e3/src/runtime/slice.go#L82


Then drew the conclusion, the capcity can be the 

capacity of  append(l1,l2) will be max(2*cap(l1), len(l1)+len(l2))


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值