🦉
Programming Notes
  • My Programming Notes
  • CKA Exam Preparation
    • Certified Kubernetes Administrator
    • Setup Minikube
    • Network Design Principles
    • Role-Based Access Control (RBAC)
    • Namespace
    • Resource Quota
    • Pod
    • Deployment
    • Deployment: Rollout
    • ConfigMap
    • Service
    • Service: kubectl expose
    • Pod: Resources Management
    • Pod & Container: Quality of Service Class
    • Pod & Container: Probes
    • Limit Range
    • Scaling: Manual
    • Scaling: Horizontal Pod Autoscaler
    • Persistent Volume & Claim
    • Secret
    • Ingress: Routing
    • Ingress: TLS
    • Ingress: Rate Limit
    • Ingress: Basic Auth
    • Ingress: CRD (Custom Resource Definition)
    • Job
    • CronJob
    • Mutli-Node Cluster
  • Golang
    • Generics
    • Context
    • Goroutines and Channels in Go
    • Goroutine: Concurrency vs Parallelism
    • Goroutine: Performance & Tradeoffs
    • JSON: omitzero
  • Rust
    • Arrays & Slices
    • Closures
    • Generics & Traits
    • Iterators
    • Run Code Simultaneously
    • String vs &str
    • Tests
    • Rustlings Exercises
      • Variables
      • Functions
      • If
      • Primitive Types
      • Vectors
      • Move Semantics
      • Structs
      • Enums and Matching Pattern
      • Strings
      • Modules
      • Hashmaps
      • Options
      • Error Handling
      • Generics
      • Traits
      • Lifetimes
      • Tests
      • Iterators
      • Smart Pointers
      • Threads
      • Macros
      • Quiz 1
      • Quiz 2
      • Quiz 3
  • Software Engineering
    • CAP Theorem
    • Circuit Breaker
    • Decoupling
    • GraphQL: Query Caching
    • HMAC Signature
    • Idempotency
    • Monolith VS Microservice
    • OWASP Top 10 2021
    • PCI DSS
    • PostgreSQL: Partitioning
    • PostgreSQL: Replication
    • Protobuf & gRPC
    • Redis: Streams
    • Resource Scaling
    • Signed URL
    • SOLID
    • Stack VS Heap
    • Stateful VS Stateless
  • Site Reliability Engineering
    • Chaos Engineering
    • Distributed Tracing
    • Kubernetes (k8s)
    • SLA, SLO, and SLI Metrics
    • Site Reliability Engineer
  • Others
    • FFMPEG Cheat sheet
Powered by GitBook
On this page
  • Heap
  • Stack
  • Golang
  • Escape Analysis
  • How to Check Allocation (Using go build or go run)
  • Examples of Stack vs Heap Allocation
  • Why It Matters?
  • Best Practices
  1. Software Engineering

Stack VS Heap

The heap and stack are two memory areas used in programming, especially for managing the lifecycle and organization of variables and data. Here's a comparison between the two:

Feature
Heap
Stack

Allocation

Manual or via garbage collection

Automatic (managed by the compiler)

Speed

Slower

Faster

Lifetime

Programmer-managed

Tied to function/block scope

Memory Size

Larger

Smaller

Fragmentation

Can fragment

Does not fragment

Use Case

Dynamic memory (e.g., large objects, data persistence beyond function calls)

Local variables, function calls

Heap

  • Purpose: Used for dynamic memory allocation, where memory is allocated and deallocated manually by the programmer (in some programming language).

  • Lifetime: Objects or data exist as long as the programmer explicitly manages them (or until garbage collection in languages like Java or Python).

  • Access: Managed via pointers or references. The programmer must explicitly keep track of allocated memory.

  • Size: Typically much larger than the stack.

  • Performance: Slower access compared to the stack because memory allocation and deallocation involve more overhead.

  • Fragmentation: Prone to fragmentation over time as memory is allocated and deallocated irregularly.

Stack

  • Purpose: Used for static memory allocation, typically for function calls, local variables, and control flow.

  • Lifetime: Memory is automatically managed. Variables are allocated when the function is called and deallocated when the function returns.

  • Access: Operates in a LIFO (Last In, First Out) manner. Access is very fast.

  • Size: Smaller and limited in size compared to the heap.

  • Performance: Faster than heap memory as allocation and deallocation are simple and automatic.

  • Fragmentation: Not prone to fragmentation because of its sequential nature.

  • Scope: Variables are only accessible within the scope of the function or block they are declared in.

The heap and stack are two memory areas used in programming, especially for managing the lifecycle and organization of variables and data. Here's a comparison between the two:

Golang

In Go, whether a variable is allocated on the stack or the heap is determined by the Go compiler through a process called escape analysis. Here's how you can identify and understand where your variables are allocated:

Escape Analysis

The Go compiler analyzes your code during compilation to decide:

  • If a variable can safely stay on the stack (local and short-lived).

  • If a variable escapes the function or its scope, it will be allocated on the heap.

Key Indicators for Heap Allocation:

  • A variable's reference is returned from a function.

  • A variable is used in a goroutine.

  • A variable's address is taken (&) and used outside its immediate scope.

How to Check Allocation (Using go build or go run)

You can explicitly see the compiler's decisions by enabling escape analysis diagnostics.

Command to See Escape Analysis:

go build -gcflags="-m" main.go
  • -gcflags="-m": Enables escape analysis messages during compilation.

  • The compiler will print messages like:

    • main.go:10: variable x escapes to heap (indicates heap allocation).

    • main.go:15: can inline func f (indicates stack allocation).

Examples of Stack vs Heap Allocation

Stack Allocation Example

func stackExample() {
    x := 42 // x is stored on the stack
    fmt.Println(x)
}

Here, x is a local variable, and it doesn't escape the function. It will be allocated on the stack.

Heap Allocation Example

func heapExample() *int {
    x := 42
    return &x // x escapes to the heap because its address is returned
}

Since x is returned by reference, it must be allocated on the heap to ensure it remains valid after the function returns.

Why It Matters?

  • Heap allocation is more expensive (slower) because it involves garbage collection.

  • Stack allocation is faster and automatically cleaned up when a function exits.

Understanding this helps optimize Go programs, particularly in performance-critical applications.

Best Practices

  • Prefer stack allocation where possible by avoiding unnecessary variable escapes.

  • Use Go's tooling to analyze your program (-gcflags="-m").

  • Don't prematurely optimize; trust Go's garbage collector and compiler unless profiling indicates a need.

PreviousSOLIDNextStateful VS Stateless

Last updated 4 months ago