WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Go · Basic · question 15 of 100

How is memory management handled in Go?

📕 Buy this interview preparation book: 100 Go questions & answers — PDF + EPUB for $5

Memory management in Go is mainly handled by the garbage collector, which automatically releases the memory occupied by unused variables and objects. Go’s memory management focuses on simplicity, efficiency, and concurrency support.

Here’s an overview of Go’s memory management:

1. **Memory allocation**: Memory in Go can be allocated using the ‘make‘ and ‘new‘ functions. ‘make‘ is used to initialize slices, maps, and channels, while ‘new‘ is employed to allocate memory for a new variable of a specified type without initializing the variable itself. When needed, Go uses the ‘sync.Pool‘ to store and retrieve temporary objects to reduce garbage collection pressure.

2. **Garbage collector**: Go uses a concurrent, tri-color, mark-sweep garbage collector that reduces the pause time and allows multiple goroutines to run simultaneously. The garbage collector is non-deterministic, which means you cannot predict when it will run, but you can request a garbage collection cycle using the ‘runtime.GC()‘ function.

3. **Escape analysis**: To improve performance, Go’s compiler performs an escape analysis on the code to determine which objects can be safely allocated on the stack instead of the heap. This helps to reduce the pressure on the garbage collector by minimizing heap allocations.

4. **Value vs. Pointer semantics**: Go encourages using value semantics by default, which passes a copy of the value to the function. This helps to reduce the shared mutable state and avoid garbage collection for local variables. Pointer semantics are useful when you need to share larger objects between functions or goroutines.

Now, let’s dive deeper into garbage collection in Go:

Go’s garbage collector (GC) follows the tri-color marking algorithm, which uses three colors to mark objects:

- **White**: Unprocessed objects (not yet visited by the GC)

- **Grey**: Objects visited by the GC but with references to unprocessed objects

- **Black**: Objects visited by the GC with all references processed

The algorithm consists of the following steps:

1. Initially, all objects are marked as white.

2. The root objects (global variables, function arguments, local variables, and goroutine stacks) are marked as grey.

3. The GC starts processing grey objects, marking them as black and turning the referenced objects into grey.

4. This process continues until there are no more grey objects.

5. All remaining white objects are considered garbage and can be removed.

Go’s GC runs concurrently with user code and mostly impacts program execution during the "mark" phase. To minimize the GC pause time, Go uses a "write barrier" mechanism during the mark phase for concurrent access by the GC and user code.

Here’s a simple example that demonstrates Go’s memory management using escape analysis, value vs. pointer semantics, and garbage collection:

package main

import (
    "fmt"
    "runtime"
    "sync"
    "time"
)

func createPointer() *int {
    x := 10                      // local variable, escape analysis
    return &x                    // escapes the stack, causes heap allocation
}

func processData(value int) int { // value semantics (pass-by-value)
    value += 10
    return value
}

func main() {
    fmt.Println("Number of CPUs:", runtime.NumCPU())

    obj := createPointer()      // heap allocated
    fmt.Println("Heap object:", *obj)

    input := 20
    result := processData(input)
    fmt.Println("Before:", input, "After:", result)

    runtime.GC()                // request garbage collection
    time.Sleep(1 * time.Second) // wait for a moment
}

In conclusion, Go’s memory management simplifies the programmer’s job by handling allocation and deallocation of memory automatically through the garbage collector. Its concurrent garbage collection, escape analysis, and efficient use of value and pointer semantics allow Go to maintain high performance and scalability in concurrent programs.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Go interview — then scores it.
📞 Practice Go — free 15 min
📕 Buy this interview preparation book: 100 Go questions & answers — PDF + EPUB for $5

All 100 Go questions · All topics