Memory Footprint: Goroutines' Tiny 2KB Stacks vs. OS Threads' Megabytes
Goroutines start with a minimal 2KB stack that dynamically grows only as needed, allowing Go programs to spawn millions of concurrent tasks. In contrast, OS threads typically allocate large, fixed-size stacks, often 1-8 MB, leading to significant memory consumption for high concurrency.
The top 3
- Go's Dynamic Stack Growth: How 2KB Becomes 1GB: Goroutines begin with a minimal 2KB stack, but the Go runtime dynamically expands it, typically by doubling its size up to 1GB on 64-bit systems, through a mechanism of reallocating and copying the stack when more space is required, preventing overflows.
- Goroutines vs. OS Threads: Over 500x Smaller Initial Stacks: Operating system threads typically reserve 1MB or more for their stack, leading to substantial memory consumption for many threads. In stark contrast, Goroutines start with a mere 2KB stack, making their initial memory footprint over 500 times smaller, enabling millions of concurrent tasks with far less RAM.
- Erlang Processes: Another Lightweight Stack Champion: Beyond Go's goroutines, Erlang processes also exemplify lightweight concurrency by using dynamically sized, small stacks. While Erlang processes maintain strict state isolation, requiring data copying for inter-process communication, both runtimes manage these user-space 'threads' significantly more efficiently than traditional OS threads.
Sources
Open the full topic