What is considered a “small” object in Go regarding stack distribution?

The code:

func MaxSmallSize() {
    a := make([]int64, 8191)
    b := make([]int64, 8192)
    _ = a
    _ = b
}

Then run go build -gcflags='-m' . 2>&1to check the details of the memory allocation. Result:

./mem.go:10: can inline MaxSmallSize
./mem.go:12: make([]int64, 8192) escapes to heap
./mem.go:11: MaxSmallSize make([]int64, 8191) does not escape

My question is: why ais it a small object, but ba large object?

make64 KB will go into a heap, and less will be allocated on the stack. Reason _MaxSmallSize = 32 << 10?

go env

GOARCH="amd64"
GOBIN=""
GOEXE=""
GOHOSTARCH="amd64"
GOHOSTOS="linux"
GOOS="linux"
GOPATH="/vagrant/gopath"
GORACE=""
GOROOT="/home/vagrant/go"
GOTOOLDIR="/home/vagrant/go/pkg/tool/linux_amd64"
CC="gcc"
GOGCCFLAGS="-fPIC -m64 -pthread -fmessage-length=0 -fdebug-prefix-map=/tmp/go-build201775001=/tmp/go-build"
CXX="g++"
CGO_ENABLED="1"
+1
source share
1 answer

Since this is not mentioned in the language specification, this is an implementation detail, and therefore it can vary depending on several things (Go version, target OS, architecture, etc.).

, cmd/compile/internal/gc.

escape-, , , cmd/compile/internal/gc/esc.go. " " esc():

func esc(e *EscState, n *Node, up *Node) {
    // ...

    // Big stuff escapes unconditionally
    // "Big" conditions that were scattered around in walk have been gathered here
    if n.Esc != EscHeap && n.Type != nil &&
        (n.Type.Width > MaxStackVarSize ||
            (n.Op == ONEW || n.Op == OPTRLIT) && n.Type.Elem().Width >= 1<<16 ||
            n.Op == OMAKESLICE && !isSmallMakeSlice(n)) {
        if Debug['m'] > 2 {
            Warnl(n.Lineno, "%v is too large for stack", n)
        }
        n.Esc = EscHeap
        addrescapes(n)
        escassignSinkNilWhy(e, n, n, "too large for stack") // TODO category: tooLarge
    }

    // ...
}

, , isSmallMakeSlice(), cmd/compile/internal/gc/walk.go:

func isSmallMakeSlice(n *Node) bool {
    if n.Op != OMAKESLICE {
        return false
    }
    l := n.Left
    r := n.Right
    if r == nil {
        r = l
    }
    t := n.Type

    return Smallintconst(l) && Smallintconst(r) && (t.Elem().Width == 0 || r.Int64() < (1<<16)/t.Elem().Width)
}

:

r.Int64() < (1<<16)/t.Elem().Width

r - ( ), t.Elem().Width - :

NumElem < 65536 / SizeElem

:

NumElem < 65536 / 8 = 8192

, []uint64, 8192 - , ( ), .

+1

Source: https://habr.com/ru/post/1671138/


All Articles