Escape Analysis in Golang

Memory Management
  1. Memory: Memory is like a brain. It is used to stored data and instructions. It’s mainly divided into three types.
  • Cache Memory
  • Primary Memory/Main Memory
  • Secondary Memory
  1. Stack: Stack is a block of memory allotted to each function. Memory is calculated on compile time.
  2. Heap: Heap is a block of memory allotted demanded by your software at runtime.
  1. Escape Analysis: Gc compiler does global escape analysis across function and package boundaries. It checks a memory that it really needs to be allocated at a heap or it could be managed within a stack itself.
  2. Function Inlining: Only short and simple functions are inlined. Function inlining is nothing but the whole code replaces the function call.
  3. Command For Escape Analysis:
go build -gcflags="-m"

1. Stack Analysis

package mainimport "fmt"func main() {
fmt.Println("Called stackAnalysis", stackAnalysis())
}
//go:noinline
func stackAnalysis() int {
data := 55
return data
}
Stack Analysis
  1. line 6:14 tells us that Called stackAnalysis which is a string literal escapes to the heap. fmt.Println() statement in code.
  2. line 6:51 tells us that function stackAnalysis called and escapes heap as every function pushed into a function stack.
  3. line 6:13 tells us that the main function is escaped to the heap same as above stackAnalysis function.
Memory Allocation

2. Heap Analysis

package mainimport "fmt"func main() {
fmt.Println("Called heapAnalysis", heapAnalysis()
}
//go:noinline
func heapAnalysis() *int {
data := 55
return &data
}
Heap Analysis
Memory Allocation

--

--

--

Software Developer, Writer(Better Programming Publication) on Medium

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Set up a release pipeline

Decomposing the Monolith with Event Storming

My own IoT deployment at Oracle Cloud Free using Autonomous DB and ML

Project Bias and the Agile Solution

12-Factor App For Dummies

With an AWS Copilot, Give Kubernetes a Second Thought — Life With Data

JVM struggles and the BEAM

Getting Started with Airflow Using Docker

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Mayur Wadekar

Mayur Wadekar

Software Developer, Writer(Better Programming Publication) on Medium

More from Medium

Install and configure Elastic Stack — II

User Creation And Authentication in Golang Part 1

Understanding Golang “Concurrency” using Arduino UNO.

CONNECT TO A POSTGRESQL DATABASE, CREATE TABLES, INSERT DATA, AND USE A FILE FROM A GITHUB PROJECT…