依据大多数资料,slice的扩容机制是当切片的容量小于1024时,进行双倍扩容;当大于1024时,进行1.25倍扩容,见如下代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
var sli = []int{}

sli = append(sli, 666)

fmt.Println(cap(sli))

sli = append(sli, 777)

fmt.Println(cap(sli))

sli = append(sli, 888)

fmt.Println(sli)

fmt.Println(cap(sli))

sli = append(sli, 999)

fmt.Println(cap(sli))

sli = append(sli, 1000)

fmt.Println(cap(sli))

输出为:

1
2
3
4
5
6
1
2
[666 777 888]
4
4
8

又见如下代码:

1
2
3
4
5
6
7
8
9
10
11
var sli2 = []int{}

for i := 0; i < 10; i++ {
sli2 = append(sli2, i)
}

fmt.Println(sli2)

fmt.Println(len(sli2))

fmt.Println(cap(sli2))

输出为:

1
2
3
[0 1 2 3 4 5 6 7 8 9]
10
16

用更”准确”的话描述,是当cap<1024时,cap的值一定是2的n次方,且cap>=len;每当发生append使len增加,如果导致len>cap,此时cap会先于append操作进行double


即有

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var sli3 = []int{}

for i := 0; i < 512; i++ {
sli3 = append(sli3, i)
}

fmt.Println(len(sli3))

fmt.Println(cap(sli3))

sli3 = append(sli3, 123)

fmt.Println(len(sli3))

fmt.Println(cap(sli3))

结果为:

1
2
3
4
512
512
513
1024

对于

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var sli4 = []int{}

for i := 0; i < 1024; i++ {
sli4 = append(sli4, i)
}

fmt.Println(len(sli4))

fmt.Println(cap(sli4))

sli4 = append(sli4, 123)

fmt.Println(len(sli4))

fmt.Println(cap(sli4))

结果为:

1
2
3
4
1024
1024
1025
1280

1024*1.25 = 1280

看似无懈可击的结果,然鹅,果真确凿如此吗?

且看切片扩容的源码,即$GOROOT/src/runtime/slice.go中的growslice方法,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127

// growslice handles slice growth during append.
// It is passed the slice element type, the old slice, and the desired new minimum capacity,
// and it returns a new slice with at least that capacity, with the old data
// copied into it.
// The new slice's length is set to the old slice's length,
// NOT to the new requested capacity.
// This is for codegen convenience. The old slice's length is used immediately
// to calculate where to write new values during an append.
// TODO: When the old backend is gone, reconsider this decision.
// The SSA backend might prefer the new length or to return only ptr/cap and save stack space.
func growslice(et *_type, old slice, cap int) slice {
if raceenabled {
callerpc := getcallerpc()
racereadrangepc(old.array, uintptr(old.len*int(et.size)), callerpc, funcPC(growslice))
}
if msanenabled {
msanread(old.array, uintptr(old.len*int(et.size)))
}

if cap < old.cap {
panic(errorString("growslice: cap out of range"))
}

if et.size == 0 {
// append should not create a slice with nil pointer but non-zero len.
// We assume that append doesn't need to preserve old.array in this case.
return slice{unsafe.Pointer(&zerobase), old.len, cap}
}

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
}
}
}

var overflow bool
var lenmem, newlenmem, capmem uintptr
// Specialize for common values of et.size.
// For 1 we don't need any division/multiplication.
// For sys.PtrSize, compiler will optimize division/multiplication into a shift by a constant.
// For powers of 2, use a variable shift.
switch {
case et.size == 1:
lenmem = uintptr(old.len)
newlenmem = uintptr(cap)
capmem = roundupsize(uintptr(newcap))
overflow = uintptr(newcap) > maxAlloc
newcap = int(capmem)
case et.size == sys.PtrSize:
lenmem = uintptr(old.len) * sys.PtrSize
newlenmem = uintptr(cap) * sys.PtrSize
capmem = roundupsize(uintptr(newcap) * sys.PtrSize)
overflow = uintptr(newcap) > maxAlloc/sys.PtrSize
newcap = int(capmem / sys.PtrSize)
case isPowerOfTwo(et.size):
var shift uintptr
if sys.PtrSize == 8 {
// Mask shift for better code generation.
shift = uintptr(sys.Ctz64(uint64(et.size))) & 63
} else {
shift = uintptr(sys.Ctz32(uint32(et.size))) & 31
}
lenmem = uintptr(old.len) << shift
newlenmem = uintptr(cap) << shift
capmem = roundupsize(uintptr(newcap) << shift)
overflow = uintptr(newcap) > (maxAlloc >> shift)
newcap = int(capmem >> shift)
default:
lenmem = uintptr(old.len) * et.size
newlenmem = uintptr(cap) * et.size
capmem, overflow = math.MulUintptr(et.size, uintptr(newcap))
capmem = roundupsize(capmem)
newcap = int(capmem / et.size)
}

// The check of overflow in addition to capmem > maxAlloc is needed
// to prevent an overflow which can be used to trigger a segfault
// on 32bit architectures with this example program:
//
// type T [1<<27 + 1]int64
//
// var d T
// var s []T
//
// func main() {
// s = append(s, d, d, d, d)
// print(len(s), "\n")
// }
if overflow || capmem > maxAlloc {
panic(errorString("growslice: cap out of range"))
}

var p unsafe.Pointer
if et.kind&kindNoPointers != 0 {
p = mallocgc(capmem, nil, false)
// The append() that calls growslice is going to overwrite from old.len to cap (which will be the new length).
// Only clear the part that will not be overwritten.
memclrNoHeapPointers(add(p, newlenmem), capmem-newlenmem)
} else {
// Note: can't use rawmem (which avoids zeroing of memory), because then GC can scan uninitialized memory.
p = mallocgc(capmem, et, true)
if writeBarrier.enabled {
// Only shade the pointers in old.array since we know the destination slice p
// only contains nil pointers because it has been cleared during alloc.
bulkBarrierPreWriteSrcOnly(uintptr(p), uintptr(old.array), lenmem)
}
}
memmove(p, old.array, lenmem)

return slice{p, old.len, newcap}
}

上面的操作是每次append一个元素,考虑另一种情形,一次性append很多元素,会发生什么呢?

当同时append进多个元素时,如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package main

import "fmt"

func main() {
a := []byte{1, 0}
a = append(a, 1, 1, 1)
fmt.Println("cap of a is ", cap(a))

b := []int{23, 51}
b = append(b, 4, 5, 6)
fmt.Println("cap of b is ", cap(b))

c := []int32{1, 23}
c = append(c, 2, 5, 6)
fmt.Println("cap of c is ", cap(c))

type D struct {
age byte
name string
}
d := []D{
{1, "123"},
{2, "234"},
}

d = append(d, D{4, "456"}, D{5, "567"}, D{6, "678"})
fmt.Println("cap of d is ", cap(d))

}

结果为:

1
2
3
4
cap of a is  8
cap of b is 6
cap of c is 8
cap of d is 5

匪夷所思…


在此使用gdb调试工具进行调试