Skip to content

Instantly share code, notes, and snippets.

@hxzhouh
Created September 25, 2024 09:46
Show Gist options
  • Select an option

  • Save hxzhouh/e09587195e2d7aa2d5f6676777c6cb16 to your computer and use it in GitHub Desktop.

Select an option

Save hxzhouh/e09587195e2d7aa2d5f6676777c6cb16 to your computer and use it in GitHub Desktop.
slice memory leak
func main() {
Demo1()
runtime.GC()
time.Sleep(1 * time.Second)
exit()
}
func exit() {
fmt.Println("Saving heap profile...")
// create a heap profile
f, err := os.Create("heap.pprof")
if err != nil {
log.Fatal("could not create heap profile: ", err)
}
runtime.GC()
//time.Sleep(1 * time.Second)
// heap profile
if err = pprof.WriteHeapProfile(f); err != nil {
log.Fatal("could not write heap profile: ", err)
}
fmt.Println("Heap profile saved in heap.pprof")
_ = f.Close()
}
var packageStr1 []string
func Demo1() {
for i := 0; i < 10; i++ {
s := createStringWithLengthOnHeap(1 << 20) //1M
packageStr1 = append(packageStr1, s[:50])
}
}
func createStringWithLengthOnHeap(i int) string {
s := make([]byte, i)
for j := 0; j < i; j++ {
s[j] = byte(j % 256 % (rand.Intn(256) + 1))
}
return string(s)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment