Home > Backend Development > Golang > How Much Memory Does a Newly Created Go Map Consume?

How Much Memory Does a Newly Created Go Map Consume?

Linda Hamilton
Release: 2024-12-06 04:36:19
Original
676 people have browsed it

How Much Memory Does a Newly Created Go Map Consume?

Estimating the Memory Reserved for Go Maps

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:

Inspecting the Map Source Code

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.

Breakdown of a Map Header

The map header itself contains several fields:

  1. int (size of the bmap array)
  2. uint8 (bucket count)
  3. uint16 (overflow buckets count)
  4. uint32 (minimum threshold before growing the map)
  5. Two unsafe pointers (for elements and pointer keys)
  6. uintptr (unused field)

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
Copy after login

Bucket Structure

Each bucket in a map is an array of eight uint8 values, which adds an additional 8 bytes:

8 * 1 = 8 bytes
Copy after login

Total Memory Consumption

Adding up the header and bucket sizes, we get a total memory consumption of:

40 + 8 = 48 bytes (64-bit architecture)
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template