go的切片扩容可以分为三种情况。
切片每次新增个数不超过原来的1倍,且每次增加数不超过1024个,且增加后总长度小于1024个,扩容为原来的2倍。
1
2
3
4
5
6
7s1 := make([]int, 0)
fmt.Printf("The capacity of s1: %d\n", cap(s1))
for i := 1; i <= 17; i++ {
s1 = append(s1, i)
fmt.Printf("s1(%d): len: %d, cap: %d\n", i, len(s1), cap(s1))
}
fmt.Println()1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19//结果:
The capacity of s1: 0
s1(1): len: 1, cap: 1
s1(2): len: 2, cap: 2
s1(3): len: 3, cap: 4
s1(4): len: 4, cap: 4
s1(5): len: 5, cap: 8
s1(6): len: 6, cap: 8
s1(7): len: 7, cap: 8
s1(8): len: 8, cap: 8
s1(9): len: 9, cap: 16
s1(10): len: 10, cap: 16
s1(11): len: 11, cap: 16
s1(12): len: 12, cap: 16
s1(13): len: 13, cap: 16
s1(14): len: 14, cap: 16
s1(15): len: 15, cap: 16
s1(16): len: 16, cap: 16
s1(17): len: 17, cap: 32切片一次新增个数超过原来1倍,但不超过1024个,且增加后总长度小于1024个,扩容增加的个数为新增个数(偶)或新增个数+1(奇)。
1
2
3
4
5
6
7
8
9
10s2 := make([]int, 10)
fmt.Printf("The capacity of s2: %d\n", cap(s2))
r1 := append(s2, make([]int, 5)...)
fmt.Printf("r1: len: %d, cap: %d\n", len(r1), cap(r1))
r2 := append(s2, make([]int, 11)...)
fmt.Printf("r2: len: %d, cap: %d\n", len(r2), cap(r2))
r3 := append(s2, make([]int, 21)...)
fmt.Printf("r3: len: %d, cap: %d\n", len(r3), cap(r3))
fmt.Printf("注意:像r2,r3 一次增加个数超过原容量的1倍,增加后结果比实际总长度预想的稍大一点 \n")
fmt.Println()1
2
3
4
5
6//结果:
The capacity of s2: 10
r1: len: 15, cap: 20
r2: len: 21, cap: 22
r3: len: 31, cap: 32
//注意:像r2,r3 一次增加个数超过原容量的1倍,增加后结果比实际总长度预想的稍大一点原切片长度超过1024,一次扩容的容量是0.25倍,每次超过预定的都是0.25累乘。
1
2
3
4
5
6
7
8
9
10
11
12// 1024 * 0.25 = 256
s3 := make([]int, 1024)
fmt.Printf("The capacity of s3: %d\n", cap(s3))
r4 := append(s3, make([]int, 200)...)
fmt.Printf("r4: len: %d, cap: %d\n", len(r4), cap(r4))
r5 := append(s3, make([]int, 256)...)
fmt.Printf("r5: len: %d, cap: %d\n", len(r5), cap(r5))
// 1280 * 0.25 = 320
r6 := append(s3, make([]int, 266)...)
fmt.Printf("r6: len: %d, cap: %d\n", len(r6), cap(r6))
fmt.Printf("注意:像r6 一次增加个数超过原容量的0.25倍,增加后结果比原容量1.25倍预想的稍大一点 \n")
fmt.Println()1
2
3
4
5
6//结果:
The capacity of s3: 1024
r4: len: 1224, cap: 1280
r5: len: 1280, cap: 1280
r6: len: 1290, cap: 1696
//注意:像r6 一次增加个数超过原容量的0.25倍,增加后结果比原容量1.25倍预想的稍大一点