Golang slice expansion rules

Golang expansion rules

Insert picture description here


举个例子来演示下
package main

import (
	"fmt"
)
func main() {
	arr1 := [4]int{1,2,3,4}
	//此时slice1为[1,2,3] 长度为3,容量为4
	slice1 :=arr1[:3]
	fmt.Println(slice1,len(slice1),cap(slice1))
	slice1 = append(slice1,5000,6000)
	fmt.Println(slice1,len(slice1),cap(slice1))
}
此时容量由原来的4扩容到了8,你以为就是简单的2倍吗?那你可真理解错了,你得知道他背后扩容的原因,我来给你计算下
1⃣️原来的容量为4,追加了5000,6000后变为了6个,此时
4*2>6,满足了脑图中的第二种情况,并且元素个数小于1024,先扩容2倍
2⃣️由于64位操作系统下,一个int类型占8个字节,所以8*8=64
3⃣️此时匹配操作系统预先分配好的内存规格,规则正好匹配了64,所以用64/8=8,所以扩容后的容量为8

Insert picture description here

咱们再来一个例子看你是否真正理解了他的扩容规则, 这个例子最后容量为10
package main

import (
	"fmt"
)
func main() {
	arr1 := [4]int{1,2,3,4}
	//此时slice1为[1,2,3] 长度为3,容量为4
	slice1 :=arr1[:3]
	fmt.Println(slice1,len(slice1),cap(slice1))
	slice1 = append(slice1,5000,6000,7000,8000,9000,10000)
	fmt.Println(slice1,len(slice1),cap(slice1))
}

···
慌不慌,你是不懂了吗?不懂我给你好好算一下
1⃣️原来容量是4,此时追加了5个元素,变为了9
2⃣️4*2<9,满足脑图中的第一个条件,由于int类型在64位操作系统下占用8个字节,所以用9*8=72
3⃣️所以此时需要匹配的内存规格为80
4⃣️用80/8=10,所以此时容量为10

Insert picture description here

···If the
number of elements is greater than 1024, I will not show you the principle. The principle is the same. After reading it carefully, you will definitely understand the expansion rules. No need to look at the others.

Summary: The slicing expansion rules are related to the number of elements you add. The
slicing expansion is related to the memory specifications allocated by the operating system you match. It is related to
the slice type you define

···

Guess you like

Origin blog.csdn.net/weixin_37509194/article/details/112001014