golang地图预留多少内存? [英] How much memory do golang maps reserve?

查看:95
本文介绍了golang地图预留多少内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个地图分配,其中未指定最初的空间,例如:

  foo:= make(map [string] int)

文档表明这里的内存分配依赖于实现。那么(怎么样)我可以告诉我的实现分配给这个映射的内存有多少?

解决方案

您可以使用Go测试工具来衡量任意复杂数据结构的大小。这是在这个答案中详细说明:如何要获得变量的变量内存大小?



要测量由 make(map [string])创建的映射的大小, int),使用以下基准函数:

  var x map [string] int 

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

使用

 执行test -bench。 -benchmem 

结果是:

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


$ b $因此,答案在于我的64位架构: 48字节

正如前文所暗示的,大小可能取决于体系结构。此外,大小可能取决于您可能传递给 make() ,你可以在这个例子中看到:

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

输出:

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

类型为 map [string] int 的地图现在初始容量为100,现在需要4176字节(在64位拱形上)。

如果未明确指定,则默认初始容量大约为7个。


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?

解决方案

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.

这篇关于golang地图预留多少内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆