Home  >  Article  >  Backend Development  >  How is GC implemented in golang functions?

How is GC implemented in golang functions?

WBOY
WBOYOriginal
2024-06-03 13:34:56993browse

In Go language functions, GC automatically reclaims memory that is no longer used. The implementation method is: tracking mark: GC thread marks all reachable objects. Clear: Clear objects marked as garbage and reclaim their memory. For example, the slice s created in function f is marked as garbage and collected when f returns.

How is GC implemented in golang functions?

Implementation of GC in Go language function

In Go language, garbage collection (GC) is automatically performed by the runtime to reclaim memory that is no longer in use. When a function returns, the GC examines the objects referenced in the function's stack frame and marks objects that are no longer needed as garbage.

The implementation method of GC

The GC of Go language adopts the generational mark-clear algorithm:

  1. Tracking mark ( Mark): The GC thread will traverse the heap memory and mark all reachable objects. A reachable object refers to an object that can be traced through a pointer from the program root object (such as global variables, method values).
  2. Sweep: After the marking is completed, the GC thread will clear all objects marked as garbage and reclaim the memory they occupy.

Practical case

The following code demonstrates the behavior of GC in a function:

package main

import "fmt"
import "runtime"

func main() {
    // 创建一个匿名函数,并在其内部分配内存
    f := func() {
        var s []int
        for i := 0; i < 1000000; i++ {
            s = append(s, i)
        }
    }

    // 调用匿名函数
    f()

    // GC 标记函数堆栈帧中的对象
    runtime.GC()

    // GC 清除不再需要的对象
    runtime.GC()
}

In this example, anonymous functionf Creates a s slice and appends 1 million integers to it. When f returns, the s slice is no longer referenced, so the GC marks it as garbage and reclaims the memory it occupies.

By running runtime.GC() before and after the anonymous function returns, we can force the GC to execute immediately and observe how the memory occupied by f is released of.

The above is the detailed content of How is GC implemented in golang functions?. 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