dongyuans61046 2017-09-18 11:17
浏览 117

golang地图会保留多少内存?

Given a map allocation where the initial space is not specified, for example:

foo := make(map[string]int)

The documentation suggests that the memory allocation here is implementation dependent. So (how) can I tell how much memory my implementation is allocating to this map?

  • 写回答

2条回答 默认 最新

  • douhu4692 2017-09-18 11:30
    关注

    You may use the Go testing tool to measure size of arbitrary complex data structures. This is detailed in this answer: How to get variable memory size of variable in golang?

    To measure the size of a map created by make(map[string]int), use the following benchmark function:

    var x map[string]int
    
    func BenchmarkEmptyMap(b *testing.B) {
        for i := 0; i < b.N; i++ {
            x = make(map[string]int)
        }
    }
    

    Executing with

    go test -bench . -benchmem
    

    The result is:

    BenchmarkEmptyMap-4     20000000   110 ns/op      48 B/op    1 allocs/op
    

    So the answer is on my 64-bit architecture: 48 bytes.

    As hinted, size may depend on architecture. Also size may depend on the initial capacity you may pass to make(), as you can see in this example:

    func BenchmarkEmptyMapCap100(b *testing.B) {
        for i := 0; i < b.N; i++ {
            x = make(map[string]int, 100)
        }
    }
    

    Output:

    BenchmarkEmptyMapCap100-4   1000000    1783 ns/op   4176 B/op    3 allocs/op
    

    A map of type map[string]int with an initial capacity of 100 now requires 4176 bytes (on 64-bit arch).

    The default initial capacity is around 7 if not specified explicitly.

    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?