Created
June 22, 2022 23:19
-
-
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
This file contains 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
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