go1.17 slice擴容機制源碼剖析詳解
擴容問題
按照一般的說法,執行下面的代碼,擴容狀态是
在容量大于1024之後每次增加原來的四分之一,如下圖
func Int64Grow() {
intSlice := make([]int64,0)
lastCap,nowCap := 0,0
fmt.Printf("%10v %10v %10v \n","nowIdx","lastCap","nowCap")
for i := 1 ;i < 3000 ; i++ {
intSlice = append(intSlice,int64(i))
nowCap = cap(intSlice)
if lastCap != nowCap {
fmt.Printf("%10d %10d %10d\n",i,len(intSlice),nowCap)
lastCap = nowCap
}
}
}
但真實的執行效果,卻是下面這樣的
把切片的類型換成
int32
,又成了如下結果
上圖中在切片容量的大小都是大于1024之後出現了問題,
網上也沒有說明白,還是自己看一下源碼
slice定義
type slice struct {
array unsafe.Pointer
len int
cap int
}
make 一個 Slice
使用兩層嵌套的if進行len和cap的範圍檢查
檢查範圍正常後申請一段記憶體并傳回,否則panic
func makeslice(et *_type, len, cap int) unsafe.Pointer {
mem, overflow := math.MulUintptr(et.size, uintptr(cap))
if overflow || mem > maxAlloc || len < 0 || len > cap {
// NOTE: Produce a 'len out of range' error instead of a
// 'cap out of range' error when someone does make([]T, bignumber).
// 'cap out of range' is true too, but since the cap is only being
// supplied implicitly, saying len is clearer.
// See golang.org/issue/4085.
mem, overflow := math.MulUintptr(et.size, uintptr(len))
if overflow || mem > maxAlloc || len < 0 {
panicmakeslicelen()
}
panicmakeslicecap()
}
return mallocgc(mem, et, true)
}
func MulUintptr(a, b uintptr) (uintptr, bool)
的主要作用就是防止溢出
uintptr
類型的傳回值,傳回ab的乘積
bool
類型的值表示a * b 是否溢出
// MulUintptr returns a * b and whether the multiplication overflowed.
// On supported platforms this is an intrinsic lowered by the compiler.
func MulUintptr(a, b uintptr) (uintptr, bool) {
if a|b < 1<<(4*sys.PtrSize) || a == 0 {
return a * b, false
}
overflow := b > MaxUintptr/a
return a * b, overflow
}
擴容函數
内容都在注釋中
// 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 {
// 如果新容量大于 2 倍的舊容量,newcap就是新容量
newcap = cap
} else {
// 如果原來的容量小于1024,則按照兩倍進行擴容
if old.cap < 1024 {
newcap = doublecap
} else {
// newcap從舊容量開始循環增加原來的 1/4 , 直到newcap大于等于新申請的容量。
// Check 0 < newcap to detect overflow
// and prevent an infinite loop.
for 0 < newcap && newcap < cap {
newcap += newcap / 4
}
// 這種情況表明 newcap 溢出了,則newcap就是新申請容量。
// Set newcap to the requested cap when
// the newcap calculation overflowed.
if newcap <= 0 {
newcap = cap
}
}
}
// overflow,lenmem,newlenmem 與記憶體的申請有關,與切片容量沒有絕對聯系,下面都注釋掉,不做讨論
// 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 {
// 類型的大小是1個位元組
case et.size == 1:
// lenmem = uintptr(old.len)
// newlenmem = uintptr(cap)
// 将新容量向上取整
capmem = roundupsize(uintptr(newcap))
// 如果 newcap 大于maxAlloc則表明溢出
// overflow = uintptr(newcap) > maxAlloc
// 擷取計算後的新容量
newcap = int(capmem)
// 類型的大小是8個位元組
case et.size == sys.PtrSize:
// 關于sys.PtrSize,粘貼一小段源碼,以下三行來自:{GOROOT}\src\runtime\internal\sys\arch.go
// // PtrSize is the size of a pointer in bytes - unsafe.Sizeof(uintptr(0)) but as an ideal constant.
// // It is also the size of the machine's native word size (that is, 4 on 32-bit systems, 8 on 64-bit).
// const PtrSize = 4 << (^uintptr(0) >> 63)
// 綜上所述,sys.PtrSize應該代表了指針類型,
// 因為指針類型是8個位元組,也是2的幂,是以要先判斷是不是指針類型或是不是和指針類型的大小一樣
// 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):
// 不是指針類型但類型大小還是2的倍數
var shift uintptr
// 如果指針的大小是8則表明是64位系統否則是32位
if sys.PtrSize == 8 {
// 計算這個表示類型的大小的數字的末尾有多少個0
// 例如:現在類型是int32 ,4個位元組,64位的系統,将會執行下面這個函數
// 因為4->000000100,是以末尾有2個0,shift也就是2
// 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)
}
// 下面這一段注釋,主要是除了capmem > maxAlloc之外,還需要檢查溢出 ,防止可能被用來觸發段錯誤
// 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"))
// }
// 與編譯器和GC有關、與申請記憶體時切片所使用的記憶體長度有關、與切片容量無關,暫不做讨論,自行翻譯
// var p unsafe.Pointer
// if et.ptrdata == 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 lenmem > 0 && 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-et.size+et.ptrdata)
// }
// }
// memmove(p, old.array, lenmem)
//
// return slice{p, old.len, newcap}
}
- 記憶體對齊函數
func roundupsize(size uintptr) uintptr
- 把給定的大小擴大到更合适的大小且是8的倍數,下面就簡稱向上取整
- 它的作用不隻是記憶體對齊,
// Returns size of the memory block that mallocgc will allocate if you ask for the size.
func roundupsize(size uintptr) uintptr {
if size < _MaxSmallSize {
if size <= smallSizeMax-8 {
return uintptr(class_to_size[size_to_class8[divRoundUp(size, smallSizeDiv)]])
} else {
return uintptr(class_to_size[size_to_class128[divRoundUp(size-smallSizeMax, largeSizeDiv)]])
}
}
if size+_PageSize < size {
return size
}
return alignUp(size, _PageSize)
}
使用到了兩個數組
class_to_size·
數組和
size_to_class128
所在的檔案
({GOROOT}\src\runtime\sizeclasses.go)
下,是一個很長的數組
const (
_MaxSmallSize = 32768
smallSizeDiv = 8
smallSizeMax = 1024
largeSizeDiv = 128
_NumSizeClasses = 68
_PageShift = 13
)
var class_to_size = [_NumSizeClasses]uint16{0, 8, 16, 24, 32, 48, 64, 80, 96, 112, 128, 144, 160, 176, 192, 208, 224, 240, 256, 288, 320, 352, 384, 416, 448, 480, 512, 576, 640, 704, 768, 896, 1024, 1152, 1280, 1408, 1536, 1792, 2048, 2304, 2688, 3072, 3200, 3456, 4096, 4864, 5376, 6144, 6528, 6784, 6912, 8192, 9472, 9728, 10240, 10880, 12288, 13568, 14336, 16384, 18432, 19072, 20480, 21760, 24576, 27264, 28672, 32768}
var class_to_allocnpages = [_NumSizeClasses]uint8{0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 2, 1, 2, 1, 3, 2, 3, 1, 3, 2, 3, 4, 5, 6, 1, 7, 6, 5, 4, 3, 5, 7, 2, 9, 7, 5, 8, 3, 10, 7, 4}
var class_to_divmagic = [_NumSizeClasses]uint32{0, ^uint32(0)/8 + 1, ^uint32(0)/16 + 1, ^uint32(0)/24 + 1, ^uint32(0)/32 + 1, ^uint32(0)/48 + 1, ^uint32(0)/64 + 1, ^uint32(0)/80 + 1, ^uint32(0)/96 + 1, ^uint32(0)/112 + 1, ^uint32(0)/128 + 1, ^uint32(0)/144 + 1, ^uint32(0)/160 + 1, ^uint32(0)/176 + 1, ^uint32(0)/192 + 1, ^uint32(0)/208 + 1, ^uint32(0)/224 + 1, ^uint32(0)/240 + 1, ^uint32(0)/256 + 1, ^uint32(0)/288 + 1, ^uint32(0)/320 + 1, ^uint32(0)/352 + 1, ^uint32(0)/384 + 1, ^uint32(0)/416 + 1, ^uint32(0)/448 + 1, ^uint32(0)/480 + 1, ^uint32(0)/512 + 1, ^uint32(0)/576 + 1, ^uint32(0)/640 + 1, ^uint32(0)/704 + 1, ^uint32(0)/768 + 1, ^uint32(0)/896 + 1, ^uint32(0)/1024 + 1, ^uint32(0)/1152 + 1, ^uint32(0)/1280 + 1, ^uint32(0)/1408 + 1, ^uint32(0)/1536 + 1, ^uint32(0)/1792 + 1, ^uint32(0)/2048 + 1, ^uint32(0)/2304 + 1, ^uint32(0)/2688 + 1, ^uint32(0)/3072 + 1, ^uint32(0)/3200 + 1, ^uint32(0)/3456 + 1, ^uint32(0)/4096 + 1, ^uint32(0)/4864 + 1, ^uint32(0)/5376 + 1, ^uint32(0)/6144 + 1, ^uint32(0)/6528 + 1, ^uint32(0)/6784 + 1, ^uint32(0)/6912 + 1, ^uint32(0)/8192 + 1, ^uint32(0)/9472 + 1, ^uint32(0)/9728 + 1, ^uint32(0)/10240 + 1, ^uint32(0)/10880 + 1, ^uint32(0)/12288 + 1, ^uint32(0)/13568 + 1, ^uint32(0)/14336 + 1, ^uint32(0)/16384 + 1, ^uint32(0)/18432 + 1, ^uint32(0)/19072 + 1, ^uint32(0)/20480 + 1, ^uint32(0)/21760 + 1, ^uint32(0)/24576 + 1, ^uint32(0)/27264 + 1, ^uint32(0)/28672 + 1, ^uint32(0)/32768 + 1}
var size_to_class8 = [smallSizeMax/smallSizeDiv + 1]uint8{0, 1, 2, 3, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15, 16, 16, 17, 17, 18, 18, 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 23, 23, 23, 23, 24, 24, 24, 24, 25, 25, 25, 25, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 30, 30, 30, 30, 30, 30, 30, 30, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32}
var size_to_class128 = [(_MaxSmallSize-smallSizeMax)/largeSizeDiv + 1]uint8{32, 33, 34, 35, 36, 37, 37, 38, 38, 39, 39, 40, 40, 40, 41, 41, 41, 42, 43, 43, 44, 44, 44, 44, 44, 45, 45, 45, 45, 45, 45, 46, 46, 46, 46, 47, 47, 47, 47, 47, 47, 48, 48, 48, 49, 49, 50, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 53, 53, 54, 54, 54, 54, 55, 55, 55, 55, 55, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 58, 58, 58, 58, 58, 58, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 61, 61, 61, 61, 61, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67}
divRoundUp(n, a uintptr) uintptr
函數在
({GOROOT}\src\runtime\subs.go)
中
// divRoundUp returns ceil(n / a).
func divRoundUp(n, a uintptr) uintptr {
// a is generally a power of two. This will get inlined and
// the compiler will optimize the division.
return (n + a - 1) / a
}
對擴容函數分析後的總結
以上代碼總結一下:
在switch語句之前:
首先判斷,如果newcap大于 2 倍的舊容量,接下來就使用newcap。
否則判斷,如果舊切片的長度小于 1024,則newcap就是舊容量的兩倍。
否則判斷,如果舊切片長度大于等于 1024,則newcap從舊容量開始循環增加原來的 1/4 , 直到newcap大于等于新申請的容量。
如果newcap計算值溢出,接下來就使用newcap。
switch中:
- 一個類型大小,如果是1,
- 那麼它最終的容量是經過
函數向上取整func roundupsize(size uintptr) uintptr
- 那麼它最終的容量是經過
- 如果一個類型大小是8:
- 它的最終容量就是在switch之前的計算所得到的容量大小乘以8,得到所需記憶體長度,
- 再将記憶體長度
向上取整之後的值除以8(相當于将容量向上取整之後再還原)roundupsize(size uintptr)
- 一個非零位元組大小類型、它的位元組長度既不是1、又不是8(機器的指針類型),而且是二的倍數:
- 計算該類型所占位元組大小的二進制尾部0的個數(記作shift)
- 再将switch之前的已經計算好的新容量,向左位移shift位,并向上對8取整,(以獲得新容量所需要記憶體的位元組長度)
- 最終的切片容量大小是:得新容量所需要記憶體的位元組長度 右移 shift位的值
- 如果以上都不符合:
- 它的最終容量就是在switch之前的計算所得到的容量大小乘以它的類型大小,得到所需記憶體長度,并其大小判斷是否溢出
- 在向上取整後除以它的類型大小
猜測:switch語句塊的作用可能是根據不同的類型大小計算合适的記憶體大小,再轉換成實際的容量
為什麼要這樣做,這樣會不會造成記憶體浪費?
我們可以想一想,go的開發者們肯定也會想到這些,是以,我們還是去源碼中找找答案
在
func roundupsize(size uintptr) uintptr
函數中,使用到了兩個數組
class_to_size·
數組和
size_to_class128
我們跳轉到其所在的檔案,所在的檔案
({GOROOT}\src\runtime\sizeclasses.go)
下,
有這兩個數組以及其他别的地方用到的數組的聲明資訊,還有go官方
檔案頭部的注釋有一個各種類型大小與記憶體的關系的表,這個表很長,如下圖(隻截取一部分)
可以初步得到結論,現在這種情況是go開發人員經過分析後得出的。
但是檔案的第一行有這樣一行注釋:
// Code generated by mksizeclasses.go; DO NOT EDIT.
這說明了我們需要找到mksizeclasses.go中去看看
在
mksizeclasses.go
中映入眼簾的注釋給了我們答案
有道翻譯:
為小的malloc大小的類生成表。
看到malloc。 概述。
選擇size類是為了舍入配置設定
請求到下一個大小的類最多浪費12.5% (1.125x)。
每個size類都有自己配置設定的頁數
當需要size類的新對象時,将其切碎。
這個頁數是被選擇的,這樣就可以分割
進入給定大小的對象的頁面最多浪費12.5% (1.125x)
的記憶體。 這裡的邊界沒有必要是
同上。
這兩種浪費源成倍增加,這是最壞的情況
對于上述的限制将是一些撥款
大小可能有26.6% (1.266x)的開銷。
在實踐中,隻有一種浪費對一個
給定大小(大小< 512主要是在彙總中浪費,
大小> 512浪費主要在頁面切割)。
對于非常小的尺寸,對齊限制強制
開銷更高。
- ok,問題解決