Skip to content

Instantly share code, notes, and snippets.

@nikzayn
Last active May 17, 2023 21:00
Show Gist options
  • Save nikzayn/2ad79ca764db841d6c9f67dacb58e568 to your computer and use it in GitHub Desktop.
Save nikzayn/2ad79ca764db841d6c9f67dacb58e568 to your computer and use it in GitHub Desktop.
In this file, we are adding and deleting 10 million elements in a map and see how it works.
package main
import (
"fmt"
"runtime"
)
func main() {
n := 10000000
m := make(map[int][128]byte)
// It will return 0 hence, at this point nothing is added it allocate elements after this
printAlloc()
// Adding 10 million elements
for i := 0; i < n; i++ {
m[i] = [128]byte{}
}
// It will return the output in MB, that how much memory it took to store 10 million element in memory
printAlloc()
// Deleting 10 million elements
for i := 0; i < n; i++ {
// https://pkg.go.dev/builtin#delete
delete(m, i)
}
// Triggers a manual GC
runtime.GC()
// Here, it will return the memory after the deallocation of KV pairs in a map
printAlloc()
// Keeps a reference to m so that the map isn’t collected
runtime.KeepAlive(m)
}
func printAlloc() {
var m runtime.MemStats
var convertToMB uint64 = 1048576
runtime.ReadMemStats(&m)
fmt.Printf("%d MB\n", m.Alloc/convertToMB)
}
// Output -
0 MB
3694 MB
2347 MB
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment