Understanding Escape Analysis in Go

Go uses escape analysis to determine the dynamic scope of Go values. Typically, go tries to store all the Go values in the function stack frame. The go compiler can predetermine which memory needs to be freed and emits machine instructions to clean it up. This way it becomes easy to clean up memory without the intervention of the Go Garbage Collector. This way of allocating memory is typically called stack allocation.

But when the compiler cannot determine the lifetime of a Go value it escapes to the heap. A value may also escape to the heap when the compiler does not know the size of the variable, or it’s too large to fit into the stack, or if the compiler cannot determine whether the variable is used after the function ends or the function stack frame is not used anymore.

CategoriesUncategorized