Strings are immutable in memory and are placed in read-only memory segments, so you can usestr[0]
Come to access, but cannot be usedstr[0]='a'
Come to modify.
Modifying a string is actually re-placed with a new address, so the performance problem that may arise when splicing a string is frequent memory allocation, such as:
func s1(ids []string) (s string) { for _, id := range ids { s += id } return }
In golang, the feature of pre-allocated memory is slices. If the memory is pre-allocated and then the strings are loaded in sequence, frequent memory allocation is avoided.
Let's take a look againstrings
Package implementation
func Join(elems []string, sep string) string { switch len(elems) { case 0: return "" case 1: return elems[0] } n := len(sep) * (len(elems) - 1) for i := 0; i < len(elems); i++ { n += len(elems[i]) } var b Builder (n) (elems[0]) for _, s := range elems[1:] { (sep) (s) } return () }
Mainly usedobject, it contains a slice.
type Builder struct { addr *Builder // of receiver, to detect copies by value buf []byte }
Builder
ofGrow
The method is to actively expand the volume of the slice.
// grow copies the buffer to a new, larger buffer so that there are at least n // bytes of capacity beyond len(). func (b *Builder) grow(n int) { buf := make([]byte, len(), 2*cap()+n) copy(buf, ) = buf } // Grow grows b's capacity, if necessary, to guarantee space for // another n bytes. After Grow(n), at least n bytes can be written to b // without another allocation. If n is negative, Grow panics. func (b *Builder) Grow(n int) { () if n < 0 { panic(": negative count") } if cap()-len() < n { (n) } }
This is the article about the detailed explanation of the performance optimization method of splicing strings in GoLang. For more related content of GoLang, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!