package main
import (
"fmt"
"runtime"
"runtime/debug"
"strings"
"unsafe"
)
func main() {
r := gen()
println("starting GC")
debug.SetGCPercent(100)
debug.SetMemoryLimit(100_000_000)
runtime.GC()
other := strings.Repeat("E", 100_000_000)
a := uintptr(unsafe.Pointer(unsafe.StringData(r)))
b := uintptr(unsafe.Pointer(unsafe.StringData(other)))
fmt.Printf("%v\n", max(a, b)-min(a, b) > uintptr(len(other))) // true
_ = other
}
func gen() string {
foo := strings.Repeat("F", 100_000_000)
runtime.SetFinalizer(&foo, func(s *string) {
println("finalized!")
})
return strings.Split(foo, "")[0]
}
This is the code that allocates a string and then uses a substring. However, even though the remaining part of the string is not accessible, it remains in memory. Is there a way to make the GC clean up the remaining part of the string without copying?