
Memory Management
Stack vs heap, escape analysis, garbage collector, memory profiling, pprof, memory leaks
1What is the main difference between stack and heap allocation in Go?
What is the main difference between stack and heap allocation in Go?
Risposta
The stack is managed automatically and allocations are extremely fast (simple stack pointer movement). Variables on the stack are automatically freed when the function returns. The heap requires the garbage collector to free memory and allocations are slower as they involve the Go runtime. Variables that survive beyond the function or whose size is not known at compile time go on the heap.
2What is escape analysis in Go?
What is escape analysis in Go?
Risposta
Escape analysis is a static analysis performed by the Go compiler to determine if a variable can remain on the stack or must be allocated on the heap. If the compiler detects that a variable is referenced outside its creation function (via a returned pointer, storage in a global variable, etc.), the variable 'escapes' and will be allocated on the heap. This analysis automatically optimizes memory allocations.
3How to view escape analysis results during compilation?
How to view escape analysis results during compilation?
Risposta
The -gcflags=-m flag allows viewing escape analysis decisions. Using -m=2 or -m=3 provides more details about why a variable escapes. For example 'go build -gcflags=-m=2' will display messages like 'moved to heap: x' to indicate that a variable was moved to the heap. This tool is essential for optimizing memory allocations in critical code.
In which case does a local variable escape to the heap?
What is the main role of the garbage collector in Go?
+21 domande da colloquio
Altri argomenti di colloquio Go
Go Basics
Go Data Structures
Go Interfaces
Error Handling
Goroutines Basics
Channels
Go Modules
HTTP Server
HTTP Client
JSON Encoding
database/sql
Context Package
Testing
Concurrency Patterns
Sync Primitives
Go Web Frameworks
REST API Design
gRPC
Reflection
Performance Optimization
Generics
Go Design Patterns
Microservices
Security & Authentication
Docker & Containerization
Kubernetes Basics
Advanced Go
CLI Development
Padroneggia Go per il tuo prossimo colloquio
Accedi a tutte le domande, flashcards, test tecnici, esercizi di code review e simulatori di colloquio.
Inizia gratis