Go memory hints

Below hints are related to very hot places of CPU/memory bound programs. And in regular (i/o bound) programs do not make much sense.

Stack vs heap

Go’s compiler goal is to allocate on the stack as much as possible. As it will reduce the amount of data that needs to be cleaned by the Garbage Collector during the app run.

Compiler performs Escape Analysis to figure out if it’s safe to keep an object on the heap.

It will move objects to the heap if:
— it cannot prove it will not be referenced after leaving current function (current stack frame)
— value is too large to fit on the stack
— the size of a value is unknown on compile time (like slices of sizes calculated in runtime).
More details are in the video:


Fields alignment

Go addresses memory in words (for 64-bit system, a word means 8 bytes).
And it wants to keep data in as less words as possible (i.e. it’s better to allocate a new word for storing int64 instead of appending it after a bool value, as it will be addressed in one cpu cycle then).

So, it’s better to group smaller fields consequentially in a struct for your program to allocate less memory while using those structures.
More on that — https://betterprogramming.pub/how-to-speed-up-your-struct-in-golang-76b846209587

Similar Posts