Escape analysis in Go
Escape analysis is a method for determining the dynamic scope of pointers.
Why would a compiler do escape analysis? Mostly for optimization purposes. According to Wikipedia:
- Converting stack allocations to heap allocations or vice-versa.
- Synchronization elision. If an object is found to be accessible from one thread only, operations on the object can be performed without synchronization.
- Breaking up objects or scalar replacement. An object may be found to be accessed in ways that do not require the object to exist as a sequential memory structure. This may allow parts (or all) of the object to be stored in CPU registers instead of in memory.
Here is an example of stack to heap conversion in Golang:
In the listing below the object declared on line 1 could be either stack or heap allocated.
The allocation type depends on the escape analysis performed by the Go compiler:
If there is a pointer to the house object and that pointer “escapes” the function then the compiler will allocate the object on the heap. Here by “escapes” we mean that the pointer will be accessible outside of the function.
If no pointer is escaping and the scope of the object is the function then the object will be allocated on the stack.
Here is the same object in context:
In our example the house object will be allocated on the heap. But for the developer the object will look like a stack allocated object. There will be no need to do pointer de-referencing when using the house object. All pointer de-referencing will happen magically under the hood. This greatly improves the readability of the code and reduces the mental strain of having to deal with pointers.
The above is an example that highlights some of the benefits of Go:
- High degree of developer productivity while not sacrificing execution speed.