Home > Backend Development > Golang > How Much Memory Does an Unspecified Go Map Allocate?

How Much Memory Does an Unspecified Go Map Allocate?

Mary-Kate Olsen
Release: 2024-12-18 15:19:25
Original
574 people have browsed it

How Much Memory Does an Unspecified Go Map Allocate?

Memory Allocation in Golang Maps: Unveiling the Underlying Structures

When creating a Go map without specifying the initial memory allocation, the actual memory usage remains a mystery. This article sheds light on how to determine the memory allocated by the implementation.

Insights from the Go Map Implementation

Delving into the source code of the Go map type, we discover that a map comprises two components: a header (hmap) and an array of buckets (bmap). Remarkably, a single bucket is allocated if the initial allocation is unspecified during map creation.

Structure of a Header (hmap)

The header consists of seven fields:

  • 1 * int
  • 2 * uint8
  • 1 * uint16
  • 1 * uint32
  • 2 * unsafe.Pointer
  • 1 * uintptr

On 64-bit machines, the size of int, uintptr, and unsafe.Pointer is 8 bytes each, giving a total of 40 bytes for the header.

Structure of a Bucket (bmap)

A bucket is an array with eight elements of type uint8, resulting in an additional 8 bytes.

Final Memory Allocation

Thus, the memory allocated for a map with one bucket consists of:

  • Header size: 40 bytes
  • Bucket size: 8 bytes
  • Total size: 48 bytes

This calculation is applicable to 64-bit architectures, and the actual size may vary slightly on different platforms.

The above is the detailed content of How Much Memory Does an Unspecified Go Map Allocate?. 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