• runtime: shrink map as elements are deleted 缩容 垃圾回收 GC 内存


    runtime: shrink map as elements are deleted

    runtime: shrink map as elements are deleted · Issue #20135 · golang/go · GitHub https://github.com/golang/go/issues/20135

    package main
    
    import (
    	"fmt"
    	"runtime"
    )
    
    func main() {
    	// runtime: shrink map as elements are deleted · Issue #20135 · golang/go · GitHub https://github.com/golang/go/issues/20135
    
    	v := struct{}{}
    
    	a := make(map[int]struct{})
    
    	for i := 0; i < 10000; i++ {
    		a[i] = v
    	}
    
    	runtime.GC()
    	printMemStats("After Map Add 100000")
    
    	for i := 0; i < 10000-1; i++ {
    		delete(a, i)
    	}
    
    	runtime.GC()
    	printMemStats("After Map Delete 9999")
    
    	for i := 0; i < 10000-1; i++ {
    		a[i] = v
    	}
    
    	runtime.GC()
    	printMemStats("After Map Add 9999 again")
    
    	a = nil
    	runtime.GC()
    	printMemStats("After Map Set nil")
    }
    
    func printMemStats(mag string) {
    	var m runtime.MemStats
    	runtime.ReadMemStats(&m)
    	fmt.Printf("%v:memory = %vKB, GC Times = %v\n", mag, m.Alloc/1024, m.NumGC)
    }
    

     

    After Map Add 100000:memory = 277KB, GC Times = 1
    After Map Delete 9999:memory = 278KB, GC Times = 2
    After Map Add 9999 again:memory = 102KB, GC Times = 3
    After Map Set nil:memory = 102KB, GC Times = 4

     

  • 相关阅读:
    学习!
    第10天:自适应高度
    第9天:第一个CSS布局实例
    nodejs in windows
    网络驱动器无法显示SVN图标问题
    nodejs获取文件修改时间
    gears旅程
    @import和link标签的差别
    evernote诡异bug
    让你的chromium支持支付宝
  • 原文地址:https://www.cnblogs.com/rsapaper/p/16284530.html
Copyright © 2020-2023  润新知