Home Backend Development Golang You may have heard of doing GC on Golang map?

You may have heard of doing GC on Golang map?

Aug 13, 2021 pm 02:26 PM
go golang

The map structure in Golang, when deleting the key-value pair, is not actually deleted, but marked. So as there are more and more key-value pairs, will it cause a lot of memory waste?

First of all, the answer is yes, it is very likely to cause OOM, and there is a discussion about this: github.com/golang/go/issues/20135. The general meaning is that in a large map, the delete operation does not actually release the memory and may cause memory OOM.

So the general approach is to rebuild the map. The container component of safemap is built into go-zero. safemap This can be avoided to a certain extent.

First let’s take a look at how map provided by go is deleted?

Native map deletion

1  package main
2
3  func main() {
4      m := make(map[int]string, 9)
5      m[1] = "hello"
6      m[2] = "world"
7      m[3] = "go"
8
9      v, ok := m[1]
10     _, _ = fn(v, ok)
11
12     delete(m, 1)
13  }
14
15 func fn(v string, ok bool) (string, bool) {
16     return v, ok
17 }
Copy after login

The test code is as above, we can passgo tool compile -S -N -l testmap.go | grep "CALL":

0x0071 00113 (test/testmap.go:4)        CALL    runtime.makemap(SB)
0x0099 00153 (test/testmap.go:5)        CALL    runtime.mapassign_fast64(SB)
0x00ea 00234 (test/testmap.go:6)        CALL    runtime.mapassign_fast64(SB)
0x013b 00315 (test/testmap.go:7)        CALL    runtime.mapassign_fast64(SB)
0x0194 00404 (test/testmap.go:9)        CALL    runtime.mapaccess2_fast64(SB)
0x01f1 00497 (test/testmap.go:10)       CALL    "".fn(SB)
0x0214 00532 (test/testmap.go:12)       CALL    runtime.mapdelete_fast64(SB)
0x0230 00560 (test/testmap.go:7)        CALL    runtime.gcWriteBarrier(SB)
0x0241 00577 (test/testmap.go:6)        CALL    runtime.gcWriteBarrier(SB)
0x0252 00594 (test/testmap.go:5)        CALL    runtime.gcWriteBarrier(SB)
0x025c 00604 (test/testmap.go:3)        CALL    runtime.morestack_noctxt(SB)
Copy after login

Execute delete on line 12, and the actual execution is runtime.mapdelete_fast64.

The parameter types of these functions are specific int64, mapdelete_fast64 operates the same as the original delete, so let’s take a lookmapdelete.

mapdelete

Long picture warning! ! !

You may have heard of doing GC on Golang map?

#The general code analysis is as above, and the specific code is left for everyone to read. In fact, the general process is:

  1. Write protection to prevent concurrent writing
  2. Query the key to be deleted if it exists
  3. If it exists, do the flag Delete mark
  4. count--

So you delete key in a large area, the actual map is stored key will not be deleted, it will just mark the current key status as empty.

In fact, the starting point is similar to the mark deletion of mysql, which prevents the same key from being inserted in the future, eliminating the need for expansion and contraction operations.

But this is inappropriate for some scenarios. If the developer will not insert the same key in the future, it is likely to cause OOM.

So in response to the above situation, go-zero developed safemap. Let's see how safemap avoids this problem?

safemap

Analyze why it is designed like this directly from the operation safemap:

You may have heard of doing GC on Golang map?

  1. Preset a deletion threshold. If triggered, it will be placed in a new preset newmap
  2. Two map It is a whole, so key can only keep one copy

So why we need to set up two map is very clear:

  1. dirtyOld As a storage principal, migration will be triggered if the delete operation reaches the threshold.
  2. dirtyNew As a temporary storage, when the threshold is reached, part of the key/value

will be stored. Therefore, during the migration operation, What we need to do is: Clear the original dirtyOld, store the stored key/value again to dirtyNew through for-range, and then dirtyNew Points to dirtyOld.

You may have questions: Doesn’t it mean that key/value is not deleted? It is just marked tophash=empty

In fact, in the for-range process, the key tophash will be filtered out

This way unnecessary keys are realized It will not be added to dirtyNew and will not affect dirtyOld.

You may have heard of doing GC on Golang map?

#This is actually the concept of the old generation and the new generation of garbage collection.

For more implementation details, you can view the source code!

Project address

github.com/tal-tech/go-zero

Welcome to use go-zero and star Support us!

The above is the detailed content of You may have heard of doing GC on Golang map?. 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 Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

How to safely read and write files using Golang? How to safely read and write files using Golang? Jun 06, 2024 pm 05:14 PM

Reading and writing files safely in Go is crucial. Guidelines include: Checking file permissions Closing files using defer Validating file paths Using context timeouts Following these guidelines ensures the security of your data and the robustness of your application.

How to configure connection pool for Golang database connection? How to configure connection pool for Golang database connection? Jun 06, 2024 am 11:21 AM

How to configure connection pooling for Go database connections? Use the DB type in the database/sql package to create a database connection; set MaxOpenConns to control the maximum number of concurrent connections; set MaxIdleConns to set the maximum number of idle connections; set ConnMaxLifetime to control the maximum life cycle of the connection.

Comparison of advantages and disadvantages of golang framework Comparison of advantages and disadvantages of golang framework Jun 05, 2024 pm 09:32 PM

The Go framework stands out due to its high performance and concurrency advantages, but it also has some disadvantages, such as being relatively new, having a small developer ecosystem, and lacking some features. Additionally, rapid changes and learning curves can vary from framework to framework. The Gin framework is a popular choice for building RESTful APIs due to its efficient routing, built-in JSON support, and powerful error handling.

How to use gomega for assertions in Golang unit tests? How to use gomega for assertions in Golang unit tests? Jun 05, 2024 pm 10:48 PM

How to use Gomega for assertions in Golang unit testing In Golang unit testing, Gomega is a popular and powerful assertion library that provides rich assertion methods so that developers can easily verify test results. Install Gomegagoget-ugithub.com/onsi/gomega Using Gomega for assertions Here are some common examples of using Gomega for assertions: 1. Equality assertion import "github.com/onsi/gomega" funcTest_MyFunction(t*testing.T){

What are the best practices for error handling in Golang framework? What are the best practices for error handling in Golang framework? Jun 05, 2024 pm 10:39 PM

Best practices: Create custom errors using well-defined error types (errors package) Provide more details Log errors appropriately Propagate errors correctly and avoid hiding or suppressing Wrap errors as needed to add context

How to save JSON data to database in Golang? How to save JSON data to database in Golang? Jun 06, 2024 am 11:24 AM

JSON data can be saved into a MySQL database by using the gjson library or the json.Unmarshal function. The gjson library provides convenience methods to parse JSON fields, and the json.Unmarshal function requires a target type pointer to unmarshal JSON data. Both methods require preparing SQL statements and performing insert operations to persist the data into the database.

Golang framework vs. Go framework: Comparison of internal architecture and external features Golang framework vs. Go framework: Comparison of internal architecture and external features Jun 06, 2024 pm 12:37 PM

The difference between the GoLang framework and the Go framework is reflected in the internal architecture and external features. The GoLang framework is based on the Go standard library and extends its functionality, while the Go framework consists of independent libraries to achieve specific purposes. The GoLang framework is more flexible and the Go framework is easier to use. The GoLang framework has a slight advantage in performance, and the Go framework is more scalable. Case: gin-gonic (Go framework) is used to build REST API, while Echo (GoLang framework) is used to build web applications.

How to solve common security problems in golang framework? How to solve common security problems in golang framework? Jun 05, 2024 pm 10:38 PM

How to address common security issues in the Go framework With the widespread adoption of the Go framework in web development, ensuring its security is crucial. The following is a practical guide to solving common security problems, with sample code: 1. SQL Injection Use prepared statements or parameterized queries to prevent SQL injection attacks. For example: constquery="SELECT*FROMusersWHEREusername=?"stmt,err:=db.Prepare(query)iferr!=nil{//Handleerror}err=stmt.QueryR

See all articles