Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go memory allocation - new objects, pointers and escape analysis

Tags:

memory

go

I read that Golang language manages memory in a smart way. Using escape analysis, go may not allocate memory when calling new, and vice versa. Can golang allocate memory with such a notation var bob * Person = & Person {2, 3}. Or always the pointer will point to the stack

like image 452
Nakem1 Avatar asked Feb 04 '26 12:02

Nakem1


1 Answers

The pointer may escape to the heap, or it may not, depends on your use case. The compiler is pretty smart. E.g. given:

type Person struct {
    b, c int
}


func foo(b, c int) int {
    bob := &Person{b, c}
    return bob.b
}

The function foo will be compiled into:

    TEXT    "".foo(SB)
    MOVQ    "".b+8(SP), AX
    MOVQ    AX, "".~r2+24(SP)
    RET

It's all on the stack here, because even though bob is a pointer, it doesn't escape this function's scope.

However, if we consider a slight (albeit artificial) modification:

var globalBob *Person

func foo(b, c int) int {
    bob := &Person{b, c}
    globalBob = bob
    return bob.b
}

Then bob escapes, and foo will be compiled to:

    TEXT    "".foo(SB), ABIInternal, $24-24
    MOVQ    (TLS), CX
    CMPQ    SP, 16(CX)
    PCDATA  $0, $-2
    JLS     foo_pc115
    PCDATA  $0, $-1
    SUBQ    $24, SP
    MOVQ    BP, 16(SP)
    LEAQ    16(SP), BP
    LEAQ    type."".Person(SB), AX
    MOVQ    AX, (SP)
    PCDATA  $1, $0
    CALL    runtime.newobject(SB)
    MOVQ    8(SP), AX
    MOVQ    "".b+32(SP), CX
    MOVQ    CX, (AX)
    MOVQ    "".c+40(SP), CX
    MOVQ    CX, 8(AX)
    PCDATA  $0, $-2
    CMPL    runtime.writeBarrier(SB), $0
    JNE     foo_pc101
    MOVQ    AX, "".globalBob(SB)
 foo_pc83:
    PCDATA  $0, $-1
    MOVQ    (AX), AX
    MOVQ    AX, "".~r2+48(SP)
    MOVQ    16(SP), BP
    ADDQ    $24, SP
    RET

Which, as you can see, invokes newobject.


These disassembly listings were generated by https://godbolt.org/, and are for go 1.16 on amd64

like image 122
Eli Bendersky Avatar answered Feb 09 '26 05:02

Eli Bendersky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!