Home >Backend Development >Golang >How Much Memory Do Go Closures Actually Consume?

How Much Memory Do Go Closures Actually Consume?

DDD
DDDOriginal
2024-10-31 21:25:29461browse

How Much Memory Do Go Closures Actually Consume?

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:

  • 16 bytes: Stores the function pointer and the pointer to the captured variable (m).
  • Variable size: Dependent on the captured variable's type and size. In this case, it's an int, so it takes 4 bytes.

Memory Footprint of Returned func() Value

The returned func() value consumes:

  • 8 bytes on 32-bit platforms, 16 bytes on 64-bit platforms: Stores the function pointer.

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 &amp;b[0]
    }
}</code>

Calling closure() allocates:

  • 16 bytes: Closure metadata (function pointer, captured variable pointer)
  • 4096 bytes: The byte array captured by the closure

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn