Heap vs Stack


Both are memory regions.

Stack (temporary to a function)

Heap (global)

Go example:

// x.go
package main

import (
    "fmt"
    "runtime"
    "time"
)

var global *int     // "global" is the name :-)

func f() {
    var x int       // heap-allocated because ...
    x = 1 
    global = &x     // ... escapes from f()
}

func g() {
    y := new(int)   // allocated on the stack
    *y = 1 
}

func main() {

    start := time.Now()
    for {
        // Run once per second
        if time.Since(start) > time.Second {
            var r runtime.MemStats
            runtime.ReadMemStats(&r)
            fmt.Printf("Heap size %d\n", r.HeapAlloc)
            fmt.Printf("Stack size %d\n", r.StackInuse)
            fmt.Printf("NumGC %d\n", r.NumGC)
            start = time.Now()
        }   

        f() 
        g()
    }   
}
go run -gcflags="-m" x.go

More

comments powered by Disqus