Golang Slice 源码分析

七秒钟回忆待续 · · 1176 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

环境

➜ go version
go version go1.15.3 darwin/amd64

初始化

  • 下标
func newSlice() []int {
    arr := [4]int{5, 7, 11, 21}
    slice := arr[1:3]
    return slice
}
  • 字面量
var s = []int{7, 11, 21}
_ = s

关键字

var s = make([]int, 0)

Compile Time

cmd/compile/internal/types/type.go

// NewSlice returns the slice Type with element type elem.
func NewSlice(elem *Type) *Type {
    if t := elem.Cache.slice; t != nil {
        if t.Elem() != elem {
            Fatalf("elem mismatch")
        }
        return t
    }

    t := New(TSLICE)
    t.Extra = Slice{Elem: elem}
    elem.Cache.slice = t
    return t
}

Runtime

reflect/value.go

type SliceHeader struct {
    Data uintptr
    Len  int
    Cap  int
}

Data 指向数组的指针
Len 切片的长度
Cap 切片的容量,数组的长度

元素访问(cmd/compile/internal/gc/ssa.go)

  • len,cap
func (s *state) expr(n *Node) *ssa.Value {
    switch n.Op {
    case OLEN, OCAP:
        switch {
        case n.Left.Type.IsSlice():
            op := ssa.OpSliceLen
            if n.Op == OCAP {
                op = ssa.OpSliceCap
            }
            return s.newValue1(op, types.Types[TINT], s.expr(n.Left))
        }
    }
}
  • INDEX
func (s *state) expr(n *Node) *ssa.Value {
    switch n.Op {
    case OINDEX:
        switch {
        case n.Left.Type.IsSlice():
            p := s.addr(n)
            return s.load(n.Left.Type.Elem(), p)
        }
}
  • APPEND(cmd/compile/internal/gc/ssa.go)
  1. inplace is false
func (s *state) append(n *Node, inplace bool) *ssa.Value {
    ptr, len, cap := s
    newlen := len + 3
    if newlen > cap {
        ptr, len, cap = growslice(s, newlen)
        newlen = len + 3 // recalculate to avoid a spill
    }
    // with write barriers, if needed:
    *(ptr+len) = e1
    *(ptr+len+1) = e2
    *(ptr+len+2) = e3
    return makeslice(ptr, newlen, cap)
}
  1. inplace is true
func (s *state) append(n *Node, inplace bool) *ssa.Value {
    a := &s
    ptr, len, cap := s
    newlen := len + 3
    if uint(newlen) > uint(cap) {
       newptr, len, newcap = growslice(ptr, len, cap, newlen)
       vardef(a)       // if necessary, advise liveness we are writing a new a
       *a.cap = newcap // write before ptr to avoid a spill
       *a.ptr = newptr // with write barrier
    }
    newlen = len + 3 // recalculate to avoid a spill
    *a.len = newlen
    // with write barriers, if needed:
    *(ptr+len) = e1
    *(ptr+len+1) = e2
    *(ptr+len+2) = e3
}
  • 扩容(runtime/slice.go)
func growslice(et *_type, old slice, cap int) slice {
    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
            }
        }
    }
}
  1. 期望容量大于当前容量的 2 倍,新容量为期望容量。
  2. 旧长度小于 1024 ,新容量为旧容量的 2 倍。
  3. 旧容量以 25% 的速率进行扩容,直到大于等于期望容量。
  • 内存字节对齐
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)
    }

切片拷贝

  • 编译时(cmd/compile/internal/gc/walk.go)
n := len(a)
if n > len(b) { 
    n = len(b) 
}
if a.ptr != b.ptr {
    memmove(a.ptr, b.ptr, n*sizeof(elem(a))) 
}
  • 运行时(src/runtime/slice.go)
func slicecopy(toPtr unsafe.Pointer, toLen int, fmPtr unsafe.Pointer, fmLen int, width uintptr) int {
    if fmLen == 0 || toLen == 0 {
        return 0
    }

    n := fmLen
    if toLen < n {
        n = toLen
    }

    if width == 0 {
        return n
    }
    size := uintptr(n) * width
    if size == 1 { // common case worth about 2x to do here
        // TODO: is this still worth it with new memmove impl?
        *(*byte)(toPtr) = *(*byte)(fmPtr) // known to be a byte pointer
    } else {
        memmove(toPtr, fmPtr, size)
    }
    return n
}

有疑问加站长微信联系(非本文作者)

本文来自:简书

感谢作者:七秒钟回忆待续

查看原文:Golang Slice 源码分析

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

1176 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传