Home Backend Development Golang Does Go language need to manually manage memory?

Does Go language need to manually manage memory?

Dec 16, 2022 pm 03:05 PM
go language

The go language does not require manual memory management; the go language has a built-in memory management function (GC mechanism), which is an automatic memory management mechanism. When the memory requested by the program from the operating system is no longer needed, garbage collection actively recycles it and reuses it for other codes to apply for memory, or returns it to the operating system. This automatic recycling process for memory-level resources is It is garbage collection; and the program component responsible for garbage collection is the garbage collector.

Does Go language need to manually manage memory?

The operating environment of this tutorial: Windows 7 system, GO version 1.18, Dell G3 computer.

go language does not require manual memory management; go language has built-in memory management function (GC mechanism), and developers do not need to care about the application and release of memory, which provides users with Come to great convenience.

What is GC and what is its use?

GC, full name Garbage Collection, is a mechanism for automatic memory management.

When the memory requested by the program from the operating system is no longer needed, garbage collection actively recycles it and reuses it for other codes to apply for memory, or returns it to the operating system. This is for memory-level resources. The automatic recycling process is garbage collection. The program component responsible for garbage collection is the garbage collector.

Garbage collection is actually a perfect example of "Simplicity is Complicated". On the one hand, programmers benefit from GC and do not need to worry about or manually apply for and release memory. GC automatically releases remaining memory when the program is running. On the other hand, GC is almost invisible to programmers. It only appears when the program needs special optimization by providing a controllable API to control the GC's running timing and running overhead.

In calculations, the memory space contains two important areas: the stack area (Stack) and the heap area (Heap); the stack area generally stores the parameters, return values ​​and local variables of function calls, and does not generate Memory fragmentation is managed by the compiler and does not need to be managed by developers; the heap area will generate memory fragmentation. In the Go language, objects in the heap area are allocated by the memory allocator and recycled by the garbage collector

Usually, garbage collection The execution process of the mutator is divided into two semi-independent components:

  • Mutator: This name essentially refers to user-mode code. Because for the garbage collector, user-mode code is only modifying the reference relationship between objects, that is, operating on the object graph (a directed graph of reference relationships between objects).

  • Collector: The code responsible for performing garbage collection.

Root object in GC

The root object is also called the root collection in the terminology of garbage collection. It is the marking process of the garbage collector. The first objects to be checked include:

  • Global variables: variables that exist throughout the entire life cycle of the program that can be determined at compile time.

  • Execution stack: Each goroutine contains its own execution stack, which contains variables on the stack and pointers to allocated heap memory blocks.

  • Register: The value of the register may represent a pointer, and these pointers involved in the calculation may point to the heap memory block allocated by some evaluator.

Garbage collection

In the Go language, the algorithm implemented by the garbage collector is A concurrent three-color mark and scan collector

The garbage collector runs concurrently with the Go program, so a write barrier algorithm is required to detect potential changes in memory. The only condition for initiating a write barrier is to stop the program for a short period of time, i.e. "Stop the World"

Does Go language need to manually manage memory?

The purpose of the write barrier is to allow the collector to remain active during collection Data integrity on the heap

1.1 Implementation principle

Go language garbage collection can be divided into clear termination, mark, and mark termination and clear four different phases, two of which produce Stop The World (STW)

Does Go language need to manually manage memory?

Clear Termination Phase

  • Pause the program, all processors will enter the safe point at this time
  • If the current garbage collection cycle is forcibly triggered, we also need to deal with the memory management unit that has not been cleaned up

Marking phase (STW)

  • Switch status to _GCmark, enable write barrier, user program assistance (Mutator Assists) and enqueue the root object

  • Resume the execution program, the marking process and the assisting user program will begin to concurrently mark the objects in the memory. The write barrier will mark both the overwritten pointers and the new pointers as gray, and all new The created objects will be directly marked in black

  • Start scanning the root object, including all Goroutine stacks, global objects, and runtime data structures not in the heap. Scanning the Goroutine stack will be paused. The current processor

  • processes the objects in the gray queue in turn, marking the objects black and marking the objects they point to gray

  • Use The distributed termination algorithm checks the remaining work and finds that after the marking phase is completed, it enters the marking termination phase

Marking termination phase (STW)

  • Pause the program, switch the state to _GCmarktermination and close the auxiliary marked user program
  • Clean the thread cache on the processor

##Cleaning phase

  • Switch the state to

    _GCoff Start the cleanup phase, initialize the cleanup state and close the write barrier

  • Recovery User program, all newly created objects will be marked in white

  • Concurrently clean up all memory management units in the background. Cleanup will be triggered when Goroutine applies for a new memory management unit

1.2 Three-color marking method

The three-color marking algorithm divides the objects in the program into three categories: white, black and gray:

    White objects - potential garbage, whose memory may be reclaimed by the garbage collector
  • Black objects - active objects, including objects that do not have any external pointers and objects that are referenced from the root object Reachable objects
  • Gray objects - active objects, because there are external pointers to white objects, the garbage collector will scan the child objects of these objects
Three-color mark garbage collection The working principle of the tool is very simple and can be summarized into the following steps:

  • Select a gray object from the collection of gray objects and mark it black

  • Mark all objects pointed to by the black object as gray to ensure that neither the object nor the objects referenced by the object will be recycled

  • Repeat the above two Steps until there are no gray objects in the object graph

Does Go language need to manually manage memory?

For more programming-related knowledge, please visit:

Programming Video! !

The above is the detailed content of Does Go language need to manually manage memory?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is the problem with Queue thread in Go's crawler Colly? What is the problem with Queue thread in Go's crawler Colly? Apr 02, 2025 pm 02:09 PM

Queue threading problem in Go crawler Colly explores the problem of using the Colly crawler library in Go language, developers often encounter problems with threads and request queues. �...

What libraries are used for floating point number operations in Go? What libraries are used for floating point number operations in Go? Apr 02, 2025 pm 02:06 PM

The library used for floating-point number operation in Go language introduces how to ensure the accuracy is...

In Go, why does printing strings with Println and string() functions have different effects? In Go, why does printing strings with Println and string() functions have different effects? Apr 02, 2025 pm 02:03 PM

The difference between string printing in Go language: The difference in the effect of using Println and string() functions is in Go...

How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? Apr 02, 2025 pm 04:54 PM

The problem of using RedisStream to implement message queues in Go language is using Go language and Redis...

What should I do if the custom structure labels in GoLand are not displayed? What should I do if the custom structure labels in GoLand are not displayed? Apr 02, 2025 pm 05:09 PM

What should I do if the custom structure labels in GoLand are not displayed? When using GoLand for Go language development, many developers will encounter custom structure tags...

Which libraries in Go are developed by large companies or provided by well-known open source projects? Which libraries in Go are developed by large companies or provided by well-known open source projects? Apr 02, 2025 pm 04:12 PM

Which libraries in Go are developed by large companies or well-known open source projects? When programming in Go, developers often encounter some common needs, ...

What is the difference between `var` and `type` keyword definition structure in Go language? What is the difference between `var` and `type` keyword definition structure in Go language? Apr 02, 2025 pm 12:57 PM

Two ways to define structures in Go language: the difference between var and type keywords. When defining structures, Go language often sees two different ways of writing: First...

When using sql.Open, why does not report an error when DSN passes empty? When using sql.Open, why does not report an error when DSN passes empty? Apr 02, 2025 pm 12:54 PM

When using sql.Open, why doesn’t the DSN report an error? In Go language, sql.Open...

See all articles