In Memory Layout of Go Closures
In contrast to JavaScript, which leverages a different closure implementation, Go closures are stored on the heap due to variable longevity.
Memory Allocation for Closures
Consider the following function that generates a closure:
<code class="go">type M int func (m *M) Adder(amount int) func() { return func() { *m = *m + amount } }</code>
When calling a := m.Adder(), two heap allocations occur:
Memory Footprint of Returned func() Value
The returned func() value consumes:
Therefore, the total memory footprint of the closure in this example is 20 bytes on 32-bit platforms, 32 bytes on 64-bit platforms.
Example:
<code class="go">func closure() func() *byte { var b [4 * 1024]byte return func() *byte { return &b[0] } }</code>
Calling closure() allocates:
Resulting in a total memory allocation of 4112 bytes.
The above is the detailed content of How Much Memory Do Go Closures Actually Consume?. For more information, please follow other related articles on the PHP Chinese website!