go之slice

slice中文切片的意思,是go獨(dú)有的類型,底層是數(shù)組,可以很方便的進(jìn)行截取,也支持?jǐn)U容、拷貝操作

slice

type slice struct {
    // 指向底層數(shù)組的指針
    array unsafe.Pointer
    // 切片的長度
    len   int
    // 切片的容量
    cap   int
}

創(chuàng)建

// 新建一個(gè)tolen長度的slice,并從from中的fromlen個(gè)元素copy到新建的slice
// 如果tolen < fromlen,則只copy tolen個(gè)元素
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
        // 判斷是否會(huì)溢出
        tomem, overflow = math.MulUintptr(et.size, uintptr(tolen))
        if overflow || tomem > maxAlloc || tolen < 0 {
            panicmakeslicelen()
        }
        // 那么拷貝長度按照fromlen來計(jì)算
        // 這里計(jì)算的是字節(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來計(jì)算
        tomem = et.size * uintptr(tolen)
        copymem = tomem
    }

    var to unsafe.Pointer
    // 下面是通過mallocgc來申請(qǐng)內(nèi)存
    // 區(qū)分slice元素類型是否是指針類型
    if et.ptrdata == 0 {
        // 如果非指針,直接申請(qǐng)字節(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.
        // 否則需要按類型申請(qǐng),因?yàn)閙allocgc會(huì)根據(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.itdecent.cn/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
}

// 新建一個(gè)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進(jìn)行分配,這個(gè)跟makeslicecopy不一樣
    // makeslicecopy之所以可以區(qū)分et是否包含指針來處理,是因?yàn)樾陆ㄍ阺lice之后還會(huì)copy部分?jǐn)?shù)據(jù)
    // 所以分配到的內(nèi)存可以手動(dòng)清零,盡量減少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個(gè)元素到toPtr中
func slicecopy(toPtr unsafe.Pointer, toLen int, fromPtr unsafe.Pointer, fromLen int, width uintptr) int {
    // 前置校驗(yàn)
    if fromLen == 0 || toLen == 0 {
        return 0
    }

    n := fromLen
    // 如果要拷貝的長度比目標(biāo)slice的長度還大,則以目標(biāo)slice的長度為準(zhǔn)
    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ū)分,如果只需要拷貝一個(gè)字節(jié),就不調(diào)用memmove函數(shù),算是一個(gè)性能優(yōu)化的點(diǎn)吧
    // 不過這里也提出了疑問,對(duì)于新版的memmove這個(gè)優(yōu)化點(diǎn)是否還有必要?
    if size == 1 { // common case worth about 2x to do here
        // TODO: is this still worth it with new memmove impl?
        // 只拷貝一個(gè)字節(jié),直接指針操作即可
        *(*byte)(toPtr) = *(*byte)(fromPtr) // known to be a byte pointer
    } else {
        // 否則就調(diào)用memmove進(jìn)行拷貝
        memmove(toPtr, fromPtr, size)
    }
    // 返回實(shí)際拷貝的長度
    return n
}

擴(kuò)容

// 根據(jù)新的容量cap對(duì)slice擴(kuò)容
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)))
    }

    // 擴(kuò)容后容量還比之前小,非法
    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}
    }

    // 這段就是計(jì)算擴(kuò)容后容量的實(shí)際邏輯
    // 1. 如果新cap比舊cap的兩倍還要大,那新cap就是實(shí)際擴(kuò)容的容量
    // 2. 1不滿足的情況下,如果舊cap < 1024,那么2*舊cap就是實(shí)際擴(kuò)容的容量
    // 3. 1,2都不滿足的情況下,循環(huán)遞增舊cap,每次遞增舊cap的1/4,直到溢出或者大于新cap,最終遞增的容量就是實(shí)際擴(kuò)容的容量
    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
            }
        }
    }

    // 下面這段是通過上面計(jì)算出來的實(shí)際擴(kuò)容量來計(jì)算通過mallocgc分配到的內(nèi)存單元mspan的對(duì)象大小
    // 因?yàn)間o的內(nèi)存分配是按照68個(gè)對(duì)象大小進(jìn)行分配的,所以分配到的內(nèi)存有可能比計(jì)算出的實(shí)際擴(kuò)容量大的
    // 這個(gè)時(shí)候我們需要通過實(shí)際分配到的內(nèi)存來反向計(jì)算出最終擴(kuò)容后的容量
    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
        // 計(jì)算實(shí)際內(nèi)存分配大小
        capmem = roundupsize(uintptr(newcap) * sys.PtrSize)
        overflow = uintptr(newcap) > maxAlloc/sys.PtrSize
        // 通過內(nèi)存大小反向計(jì)算容量
        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}
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 原文鏈接:https://blog.thinkeridea.com/201901/go/slice_de_yi_x...
    戚銀閱讀 1,691評(píng)論 0 0
  • 前言 用過go語言的親們都知道,slice(中文翻譯為切片)在編程中經(jīng)常用到,它代表變長的序列,序列中每個(gè)元素都有...
    空即是色即是色即是空閱讀 1,713評(píng)論 1 1
  • slice的存儲(chǔ)結(jié)構(gòu) slice代表變長的序列,它的底層是數(shù)組。一個(gè)切片由3部分組成:指針、長度和容量。指針指向底...
    cindywang閱讀 5,672評(píng)論 0 0
  • 原文地址:深入理解 Go Slice 是什么 在 Go 中,Slice(切片)是抽象在 Array(數(shù)組)之上的特...
    EDDYCJY閱讀 1,355評(píng)論 0 12
  • 1. 前言 Slice又稱動(dòng)態(tài)數(shù)組,依托數(shù)組實(shí)現(xiàn),可以方便的進(jìn)行擴(kuò)容、傳遞等,實(shí)際使用中比數(shù)組更靈活。 正因?yàn)殪`活...
    淘小鋪刀仔閱讀 857評(píng)論 0 0

友情鏈接更多精彩內(nèi)容