search
HomeBackend DevelopmentGolangLearn about the reuse of golang slice and string in one article

Learn about the reuse of golang slice and string in one article

Jul 16, 2021 pm 03:34 PM
golangslicestringPerformance optimization

Compared with c/c, a big improvement of golang is the introduction of gc mechanism, which no longer requires users to manage memory by themselves , greatly reducing the bugs introduced by the program due to memory leaks, but at the same time gc also brings additional performance overhead, and sometimes even causes gc to become a performance bottleneck due to improper use. Therefore, when designing golang programs, special attention should be paid to the object Reuse to reduce pressure on gc. Slice and string are the basic types of golang. Understanding the internal mechanisms of these basic types will help us better reuse these objects

The internal structure of slice and string

The internal structure of slice and string The structure can be found in $GOROOT/src/reflect/value.go

type StringHeader struct {
    Data uintptr
    Len  int
}

type SliceHeader struct {
    Data uintptr
    Len  int
    Cap  int
}

You can see that a string contains a data pointer and a length, and the length is immutable

slice contains a data pointer, a length and a capacity. When the capacity is not enough, new memory will be re-applied. The Data pointer will point to the new address and the original address space will be released.

From these structures It can be seen that the assignment of string and slice, including passing it as a parameter, is just a shallow copy of the Data pointer like the custom structure

slice reuse

append operation

si1 := []int{1, 2, 3, 4, 5, 6, 7, 8, 9}
si2 := si1
si2 = append(si2, 0)
Convey("重新分配内存", func() {
    header1 := (*reflect.SliceHeader)(unsafe.Pointer(&si1))
    header2 := (*reflect.SliceHeader)(unsafe.Pointer(&si2))
    fmt.Println(header1.Data)
    fmt.Println(header2.Data)
    So(header1.Data, ShouldNotEqual, header2.Data)
})

si1 and si2 both point to the same array at first. When the append operation is performed on si2, because the original Cap value is not enough, new space needs to be reapplied, so the Data value changes. In $GOROOT /src/reflect/value.go This file also contains strategies for new cap values. In the function grow, when the cap is less than 1024, it will grow exponentially, exceeding , each time it increases by 25%, and this memory growth not only consumes additional performance for data copying (copying from the old address to the new address), the release of the old address memory will also cause additional burden on gc, so If you can know the length of the data, try to use make([]int, len, cap) to pre-allocate memory. If you don’t know the length, you can consider the following memory reuse method

Memory reuse

si1 := []int{1, 2, 3, 4, 5, 6, 7, 8, 9}
si2 := si1[:7]
Convey("不重新分配内存", func() {
    header1 := (*reflect.SliceHeader)(unsafe.Pointer(&si1))
    header2 := (*reflect.SliceHeader)(unsafe.Pointer(&si2))
    fmt.Println(header1.Data)
    fmt.Println(header2.Data)
    So(header1.Data, ShouldEqual, header2.Data)
})

Convey("往切片里面 append 一个值", func() {
    si2 = append(si2, 10)
    Convey("改变了原 slice 的值", func() {
        header1 := (*reflect.SliceHeader)(unsafe.Pointer(&si1))
        header2 := (*reflect.SliceHeader)(unsafe.Pointer(&si2))
        fmt.Println(header1.Data)
        fmt.Println(header2.Data)
        So(header1.Data, ShouldEqual, header2.Data)
        So(si1[7], ShouldEqual, 10)
    })
})

si2 is a slice of si1. From the first piece of code, you can see that the slice does not reallocate memory. The Data pointers of si2 and si1 point to the same slice address, while the second piece of code It can be seen that when we append a new value to si2, we find that there is still no memory allocation, and this operation causes the value of si1 to also change, because both point to the same Data area. Use this feature , we only need to let si1 = si1[:0] to continuously clear the contents of si1 and realize memory reuse

PS: You can use copy(si2, si1) Implement deep copy

string

Convey("字符串常量", func() {
    str1 := "hello world"
    str2 := "hello world"
    Convey("地址相同", func() {
        header1 := (*reflect.StringHeader)(unsafe.Pointer(&str1))
        header2 := (*reflect.StringHeader)(unsafe.Pointer(&str2))
        fmt.Println(header1.Data)
        fmt.Println(header2.Data)
        So(header1.Data, ShouldEqual, header2.Data)
    })
})

This example is relatively simple. The string constants use the same address area

Convey("相同字符串的不同子串", func() {
    str1 := "hello world"[:6]
    str2 := "hello world"[:5]
    Convey("地址相同", func() {
        header1 := (*reflect.StringHeader)(unsafe.Pointer(&str1))
        header2 := (*reflect.StringHeader)(unsafe.Pointer(&str2))
        fmt.Println(header1.Data, str1)
        fmt.Println(header2.Data, str2)
        So(str1, ShouldNotEqual, str2)
        So(header1.Data, ShouldEqual, header2.Data)
    })
})

Different substrings of the same string will not apply for additional new memory, but it should be noted that the same string here refers to str1.Data == str2.Data && str1.Len == str2. Len, instead of str1 == str2, the following example can illustrate str1 == str2 but its Data is not the same

Convey("不同字符串的相同子串", func() {
    str1 := "hello world"[:5]
    str2 := "hello golang"[:5]
    Convey("地址不同", func() {
        header1 := (*reflect.StringHeader)(unsafe.Pointer(&str1))
        header2 := (*reflect.StringHeader)(unsafe.Pointer(&str2))
        fmt.Println(header1.Data, str1)
        fmt.Println(header2.Data, str2)
        So(str1, ShouldEqual, str2)
        So(header1.Data, ShouldNotEqual, header2.Data)
    })
})

actually for characters String, you just need to remember one thing, string is immutable, any string operation will not apply for additional memory (for only internal data pointers), I once cleverly designed a cache to store strings , to reduce the space occupied by repeated strings. In fact, unless the string itself is created from []byte, otherwise, the string itself is a substring of another string (such as Strings obtained through strings.Split) will not apply for additional space. Doing so is simply unnecessary.

For more golang related technical articles, please visit the golang tutorial column!

The above is the detailed content of Learn about the reuse of golang slice and string in one article. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
Golang and Python: Understanding the DifferencesGolang and Python: Understanding the DifferencesApr 18, 2025 am 12:21 AM

The main differences between Golang and Python are concurrency models, type systems, performance and execution speed. 1. Golang uses the CSP model, which is suitable for high concurrent tasks; Python relies on multi-threading and GIL, which is suitable for I/O-intensive tasks. 2. Golang is a static type, and Python is a dynamic type. 3. Golang compiled language execution speed is fast, and Python interpreted language development is fast.

Golang vs. C  : Assessing the Speed DifferenceGolang vs. C : Assessing the Speed DifferenceApr 18, 2025 am 12:20 AM

Golang is usually slower than C, but Golang has more advantages in concurrent programming and development efficiency: 1) Golang's garbage collection and concurrency model makes it perform well in high concurrency scenarios; 2) C obtains higher performance through manual memory management and hardware optimization, but has higher development complexity.

Golang: A Key Language for Cloud Computing and DevOpsGolang: A Key Language for Cloud Computing and DevOpsApr 18, 2025 am 12:18 AM

Golang is widely used in cloud computing and DevOps, and its advantages lie in simplicity, efficiency and concurrent programming capabilities. 1) In cloud computing, Golang efficiently handles concurrent requests through goroutine and channel mechanisms. 2) In DevOps, Golang's fast compilation and cross-platform features make it the first choice for automation tools.

Golang and C  : Understanding Execution EfficiencyGolang and C : Understanding Execution EfficiencyApr 18, 2025 am 12:16 AM

Golang and C each have their own advantages in performance efficiency. 1) Golang improves efficiency through goroutine and garbage collection, but may introduce pause time. 2) C realizes high performance through manual memory management and optimization, but developers need to deal with memory leaks and other issues. When choosing, you need to consider project requirements and team technology stack.

Golang vs. Python: Concurrency and MultithreadingGolang vs. Python: Concurrency and MultithreadingApr 17, 2025 am 12:20 AM

Golang is more suitable for high concurrency tasks, while Python has more advantages in flexibility. 1.Golang efficiently handles concurrency through goroutine and channel. 2. Python relies on threading and asyncio, which is affected by GIL, but provides multiple concurrency methods. The choice should be based on specific needs.

Golang and C  : The Trade-offs in PerformanceGolang and C : The Trade-offs in PerformanceApr 17, 2025 am 12:18 AM

The performance differences between Golang and C are mainly reflected in memory management, compilation optimization and runtime efficiency. 1) Golang's garbage collection mechanism is convenient but may affect performance, 2) C's manual memory management and compiler optimization are more efficient in recursive computing.

Golang vs. Python: Applications and Use CasesGolang vs. Python: Applications and Use CasesApr 17, 2025 am 12:17 AM

ChooseGolangforhighperformanceandconcurrency,idealforbackendservicesandnetworkprogramming;selectPythonforrapiddevelopment,datascience,andmachinelearningduetoitsversatilityandextensivelibraries.

Golang vs. Python: Key Differences and SimilaritiesGolang vs. Python: Key Differences and SimilaritiesApr 17, 2025 am 12:15 AM

Golang and Python each have their own advantages: Golang is suitable for high performance and concurrent programming, while Python is suitable for data science and web development. Golang is known for its concurrency model and efficient performance, while Python is known for its concise syntax and rich library ecosystem.

See all articles

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)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor