When working with Go maps, it's often useful to have an estimate of the memory they consume. While the documentation states that the initial memory allocation is implementation-dependent, here's a deeper dive into how you can determine this:
Go maps are built upon two types: hmap (header) and bmap (bucket array). Examining the source code reveals that when no initial space is specified (foo := make(map[string]int)), only a single bucket is created within the map.
The map header itself contains several fields:
Assuming a 64-bit architecture, the size of int, uintptr, and unsafe.Pointer is 8 bytes each. This gives us a header size of:
1 * 8 + 1 * 1 + 1 * 2 + 1 * 4 + 2 * 8 + 1 * 8 = 40 bytes
Each bucket in a map is an array of eight uint8 values, which adds an additional 8 bytes:
8 * 1 = 8 bytes
Adding up the header and bucket sizes, we get a total memory consumption of:
40 + 8 = 48 bytes (64-bit architecture)
This estimate can be used to approximate the memory usage of a newly created Go map with no initial space specified.
The above is the detailed content of How Much Memory Does a Newly Created Go Map Consume?. For more information, please follow other related articles on the PHP Chinese website!