Created
September 25, 2024 09:46
-
-
Save hxzhouh/e09587195e2d7aa2d5f6676777c6cb16 to your computer and use it in GitHub Desktop.
slice memory leak
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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