Skip to content

Instantly share code, notes, and snippets.

@CAFxX
Last active January 29, 2020 03:06
Show Gist options
  • Select an option

  • Save CAFxX/ff5db9f67f338cd548de9e2ef4793096 to your computer and use it in GitHub Desktop.

Select an option

Save CAFxX/ff5db9f67f338cd548de9e2ef4793096 to your computer and use it in GitHub Desktop.
ShrinkMap
package shrinkmap
import "reflect"
// ShrinkMap shrinks the capacity of the supplied map. It panics if m is not a
// map. ShrinkMap may temporarily require double the amount of memory used by m.
// It is recommended not to hold iterators to the map while it is being shrunk.
// So much fail because of no generics. T_T
func ShrinkMap(m interface{}) interface{} {
M := reflect.ValueOf(m)
if M.Kind() != reflect.Map {
panic("not a map")
}
N := reflect.MakeMapWithSize(M.Type(), M.Len())
Mi := M.MapRange()
for Mi.Next() {
K := Mi.Key()
V := Mi.Value()
N.SetMapIndex(K, V)
}
return N.Interface()
}
package shrinkmap
import "fmt"
import "testing"
func TestShrinkMap(_ *testing.T) {
m := make(map[int]struct{})
for i := 0; i < 1000; i++ {
m[i] = struct{}{}
}
for i := 0; i < 900; i++ {
delete(m, i)
}
// the following line is the same as:
// {
// _m := make(map[int]struct{}, len(m))
// for k, v := range m {
// _m[k] = v
// }
// m = _m
// }
m = ShrinkMap(m).(map[int]struct{})
fmt.Println(len(m))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment