Skip to content

Instantly share code, notes, and snippets.

@druminski
Created June 13, 2016 14:33
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save druminski/5e529d6c2ada12cb0a99fd5e8e3c3f8e to your computer and use it in GitHub Desktop.
Save druminski/5e529d6c2ada12cb0a99fd5e8e3c3f8e to your computer and use it in GitHub Desktop.
package main
import (
_ "net/http/pprof"
"net/http"
"log"
"math/rand"
"runtime"
"fmt"
"hash/fnv"
)
const (
entries = 10000001
repeats = 100000
)
var charsRunes = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
func main() {
go func () {
log.Println(http.ListenAndServe("localhost:6060", nil))
}()
hashmap := make(map[uint64]bool, entries)
hashes := make([]uint64, entries)
for repeat := 0; repeat < repeats; repeat++ {
fmt.Printf("==== \nRepeat: %6d \n", repeat)
fmt.Printf("Number of elements: %6d \n", len(hashmap))
printAllocs()
for index := 0; index < entries - 1; index++ {
key := generateKey()
hashes[index] = key
hashmap[key] = true
delete(hashmap, hashes[index + 1])
}
key := generateKey()
hashes[entries - 1] = key
hashmap[entries - 1] = true
delete(hashmap, hashes[0])
}
}
func generateKey() uint64 {
return hash64(randomString(64))
}
func hash64(s string) uint64 {
h := fnv.New64a()
h.Write([]byte(s))
return h.Sum64()
}
func randomString(n int) string {
b := make([]rune, n)
for i := range b {
b[i] = charsRunes[rand.Intn(len(charsRunes))]
}
return string(b)
}
func printAllocs() {
var m runtime.MemStats
runtime.ReadMemStats(&m)
fmt.Printf("Heap size: %6d MB \n", m.Alloc / 1e6)
}
@druminski
Copy link
Author

go build map_leak.go
./map_leak.go

...
go tool pprof ./map_leak  http://localhost:6060/debug/pprof/heap

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment