How Memory Layout of Go Closures Unveils Their Heap Allocation
Go closures are notable for their ability to refer to variables defined in their surrounding functions. This raises questions about their memory allocation and layout.
Memory Layout of Closures
Go's function literals (essentially closures) can be assigned to variables or invoked directly. A closure retains variables from its surrounding function, which persist until they are no longer accessible.
According to the Go Programming Language Specification, variables that survive function calls are placed on the heap. Thus, Go closures are stored on the heap.
Example Analysis
Consider the function closure():
<code class="go">func closure() func() *byte { var b [4 * 1024]byte return func() *byte { return &b[0] } }</code>
Each closure() invocation results in two heap allocations:
Thus, a total of 4112 bytes are allocated for each closure.
Key Takeaway
Go closures are simply variables that live on the heap, ensuring the persistence of shared variables between the closure and its surrounding function. This straightforward memory layout allows for efficient allocation and access of closure variables.
The above is the detailed content of Why are Go Closures Allocated on the Heap?. For more information, please follow other related articles on the PHP Chinese website!