slice中文切片的意思如叼,是go獨有的類型诀艰,底層是數(shù)組懦冰,可以很方便的進行截取颂砸,也支持擴容噪奄、拷貝操作
slice
type slice struct {
// 指向底層數(shù)組的指針
array unsafe.Pointer
// 切片的長度
len int
// 切片的容量
cap int
}
創(chuàng)建
// 新建一個tolen長度的slice,并從from中的fromlen個元素copy到新建的slice
// 如果tolen < fromlen人乓,則只copy tolen個元素
func makeslicecopy(et *_type, tolen int, fromlen int, from unsafe.Pointer) unsafe.Pointer {
var tomem, copymem uintptr
// 如果新建的slice長度比要拷貝的長度大
if uintptr(tolen) > uintptr(fromlen) {
var overflow bool
// 判斷是否會溢出
tomem, overflow = math.MulUintptr(et.size, uintptr(tolen))
if overflow || tomem > maxAlloc || tolen < 0 {
panicmakeslicelen()
}
// 那么拷貝長度按照fromlen來計算
// 這里計算的是字節(jié)數(shù)
copymem = et.size * uintptr(fromlen)
} else {
// fromlen is a known good length providing and equal or greater than tolen,
// thereby making tolen a good slice length too as from and to slices have the
// same element width.
// 否則拷貝長度按照tolen來計算
tomem = et.size * uintptr(tolen)
copymem = tomem
}
var to unsafe.Pointer
// 下面是通過mallocgc來申請內(nèi)存
// 區(qū)分slice元素類型是否是指針類型
if et.ptrdata == 0 {
// 如果非指針勤篮,直接申請字節(jié)流
to = mallocgc(tomem, nil, false)
// 并將copy之后多余的部分清零
if copymem < tomem {
memclrNoHeapPointers(add(to, copymem), tomem-copymem)
}
} else {
// Note: can't use rawmem (which avoids zeroing of memory), because then GC can scan uninitialized memory.
// 否則需要按類型申請,因為mallocgc會根據(jù)et來判斷是否需要按照有指針處理
to = mallocgc(tomem, et, true)
if copymem > 0 && writeBarrier.enabled {
// Only shade the pointers in old.array since we know the destination slice to
// only contains nil pointers because it has been cleared during alloc.
// 由于GC的存在, 在拷貝前, 如果et包含指針, 需要開啟寫屏障
// 關(guān)于寫屏障色罚,可以看下 http://www.reibang.com/p/64240319ed60
bulkBarrierPreWriteSrcOnly(uintptr(to), uintptr(from), copymem)
}
}
if raceenabled {
callerpc := getcallerpc()
pc := funcPC(makeslicecopy)
racereadrangepc(from, copymem, callerpc, pc)
}
if msanenabled {
msanread(from, copymem)
}
// 拷貝
memmove(to, from, copymem)
return to
}
// 新建一個len長cap容量的slice
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()
}
// 直接調(diào)用mallocgc進行分配碰缔,這個跟makeslicecopy不一樣
// makeslicecopy之所以可以區(qū)分et是否包含指針來處理,是因為新建完slice之后還會copy部分數(shù)據(jù)
// 所以分配到的內(nèi)存可以手動清零戳护,盡量減少mallocgc的工作金抡,提高內(nèi)存分配的效率
return mallocgc(mem, et, true)
}
拷貝
// slicecopy is used to copy from a string or slice of pointerless elements into a slice.
// 從fromPtr中拷貝fromLen個元素到toPtr中
func slicecopy(toPtr unsafe.Pointer, toLen int, fromPtr unsafe.Pointer, fromLen int, width uintptr) int {
// 前置校驗
if fromLen == 0 || toLen == 0 {
return 0
}
n := fromLen
// 如果要拷貝的長度比目標slice的長度還大,則以目標slice的長度為準
if toLen < n {
n = toLen
}
// 元素長度是0腌且,無效操作
if width == 0 {
return n
}
size := uintptr(n) * width
if raceenabled {
callerpc := getcallerpc()
pc := funcPC(slicecopy)
racereadrangepc(fromPtr, size, callerpc, pc)
racewriterangepc(toPtr, size, callerpc, pc)
}
if msanenabled {
msanread(fromPtr, size)
msanwrite(toPtr, size)
}
// 這里做了區(qū)分梗肝,如果只需要拷貝一個字節(jié),就不調(diào)用memmove函數(shù)铺董,算是一個性能優(yōu)化的點吧
// 不過這里也提出了疑問巫击,對于新版的memmove這個優(yōu)化點是否還有必要?
if size == 1 { // common case worth about 2x to do here
// TODO: is this still worth it with new memmove impl?
// 只拷貝一個字節(jié),直接指針操作即可
*(*byte)(toPtr) = *(*byte)(fromPtr) // known to be a byte pointer
} else {
// 否則就調(diào)用memmove進行拷貝
memmove(toPtr, fromPtr, size)
}
// 返回實際拷貝的長度
return n
}
擴容
// 根據(jù)新的容量cap對slice擴容
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}
}
// 這段就是計算擴容后容量的實際邏輯
// 1. 如果新cap比舊cap的兩倍還要大匆绣,那新cap就是實際擴容的容量
// 2. 1不滿足的情況下,如果舊cap < 1024什黑,那么2*舊cap就是實際擴容的容量
// 3. 1,2都不滿足的情況下崎淳,循環(huán)遞增舊cap,每次遞增舊cap的1/4愕把,直到溢出或者大于新cap拣凹,最終遞增的容量就是實際擴容的容量
newcap := old.cap
doublecap := newcap + newcap
if cap > doublecap {
newcap = cap
} else {
if old.cap < 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
}
}
}
// 下面這段是通過上面計算出來的實際擴容量來計算通過mallocgc分配到的內(nèi)存單元mspan的對象大小
// 因為go的內(nèi)存分配是按照68個對象大小進行分配的,所以分配到的內(nèi)存有可能比計算出的實際擴容量大的
// 這個時候我們需要通過實際分配到的內(nèi)存來反向計算出最終擴容后的容量
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
// 計算實際內(nèi)存分配大小
capmem = roundupsize(uintptr(newcap) * sys.PtrSize)
overflow = uintptr(newcap) > maxAlloc/sys.PtrSize
// 通過內(nèi)存大小反向計算容量
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"))
}
// 這里跟makeslicecopy里的處理邏輯一致恨豁,不贅述
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}
}