This is a simple example of intercepting a string in a sliced manner. Actually, no memory copy has occurred, but just a reference is created. Often the functions in the standard library also truncate the string.
This can be simple and efficient, because no new memory is allocated, which is often very effective.
However, if the life cycle of the original string is very short and very large, and the life cycle of the obtained substring is long enough and very short, then GC
will not release the original that is no longer used in the substring lifetime. String memory, which causes a memory leak.
There are such problems in most of the actual programs, but they are not so unbearable, only minor short-term problems, which can be ignored without pursuing extreme performance.
We should still pay attention to this issue and deal with it when necessary, but not too often, and extreme situations rarely occur.
Here is a Chinese introduction to strings, maybe there will be some help [string 优化误区及建议] (https://blog.thinkeridea.com/201902/go/string_ye_shi_yin_yong_lei_xing.html)
package main
import (
"fmt"
"reflect"
"strings"
"unsafe"
)
func main() {
s := strings.Repeat("A", 2000)
s1 := s[5:10]
fmt.Println((*reflect.StringHeader)(unsafe.Pointer(&s)).Data) // 824634433536
fmt.Println((*reflect.StringHeader)(unsafe.Pointer(&s1)).Data) // 824634433541
// Changing the s string type to [] byte does not produce duplication, but only parsing the string data stored in the s variable in memory in the way of byte
sh := (*reflect.StringHeader)(unsafe.Pointer(&s))
bs := *(*[]byte)(unsafe.Pointer(&reflect.SliceHeader{
Data: sh.Data,
Len: sh.Len,
Cap: sh.Len,
}))
// Modify one segment of data, which is referenced by s1.
copy(bs[5:10], strings.Repeat("B", 5))
// It is found that the data of s1 has changed.
fmt.Println(s1) // BBBBB
}