Jun 25, 2018

[Go] stack memory size

runtime/debug/#SetMaxStack

stacks are not essential for Go programs.
Go compiler/runtime can allocate all memory block on heap.
Supporting stacks is just to make Go programs run more efficiently:
  • allocating memory blocks on stacks is much faster than on heap. 
  • memory blocks allocated on a stack don't need to be garbage collected. 
  • stack memory blocks are more CPU cache friendly than heap ones.

Some facts:
  • If a field of a struct value escapes to heap, then the whole struct value will also escape to heap.
  • If an element of an array value escapes to heap, then the whole array value will also escape to heap.
  • If an element of a slice value escapes to heap, then all the elements of the slice will also escape to heap.
  • If a non-nil slice value escapes to heap, then its elements will also escape to heap.
A memory block created by calling new function may be allocated on heap or stacks. This is different to C++.

runtime.KeepAlive function calls are often needed if unsafe pointers are involved.

To check which local values (value parts) will escape to heap at run time:
$ go build -gcflags -m


No comments:

Post a Comment

Note: Only a member of this blog may post a comment.