Go

Memory Management

Stack vs heap, escape analysis, garbage collector, memory profiling, pprof, memory leaks

24 คำถามสัมภาษณ์·
Senior
1

What is the main difference between stack and heap allocation in Go?

คำตอบ

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.

2

What is escape analysis in Go?

คำตอบ

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.

3

How to view escape analysis results during compilation?

คำตอบ

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.

4

In which case does a local variable escape to the heap?

5

What is the main role of the garbage collector in Go?

+21 คำถามสัมภาษณ์

เชี่ยวชาญ Go สำหรับการสัมภาษณ์ครั้งถัดไป

เข้าถึงคำถามทั้งหมด flashcards แบบทดสอบเทคนิค แบบฝึกหัด code review และตัวจำลองสัมภาษณ์

เริ่มใช้ฟรี