Skip to content

Instantly share code, notes, and snippets.

@xeoncross
Created June 22, 2022 23:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xeoncross/cfbe0a5d40be7284a6a0edbe9fe8f47f to your computer and use it in GitHub Desktop.
Save xeoncross/cfbe0a5d40be7284a6a0edbe9fe8f47f to your computer and use it in GitHub Desktop.
Keep the keys with the highest values in a map https://go.dev/play/p/E-PQldhgz4M
package main
import "fmt"
func BenchmarkMapIteration(b *testing.B) {
size := 1000
ranked := make(map[int]uint8, size)
for i := 1; i < size; i++ {
ranked[i] = uint8(i % 8)
}
// We have a fixed-size "ranked" map which we want to keep only the "highest" values in
// So, as new values come along we loop through the whole array to see if something lower exists we can
// remove and replace with the new value
var changes int
b.ResetTimer()
for i := 0; i < b.N; i++ {
key := i + size
value := uint8(i % 8)
sK, sV := -1, value
for k, v := range ranked {
if v < sV {
sK = k
sV = v
}
}
// Found something smaller? Remove it and add this
if sK != -1 {
changes++
delete(ranked, sK)
ranked[key] = value
}
}
b.Logf("%d keys left, %d changes\n", len(ranked), changes)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment