Memory Allocation in Go Maps: An Implementation-Specific Inquiry
In the world of Go mapping, memory allocation presents an enigma. The absence of an initial capacity parameter when initializing a map leaves the size of the allocated space subject to the whims of the implementation. But how can we unveil the secrets of this hidden allocation?
Delving into the depths of the Go map source code reveals a structure consisting of a header and an array of buckets. In the case of unspecified initial space, the map comprises only a single bucket.
The header itself is a veritable labyrinth of fields:
On 64-bit machines, the size of int, uintptr, and unsafe.Pointer aligns with the word size (8 bytes). This composition yields a total of 40 bytes for the header.
Now, let's turn our attention to the bucket, which houses an array of 8 uint8 elements. This contributes an additional 8 bytes to the overall tally.
Combining these components, we arrive at a grand total of 48 bytes (for 64-bit architectures). Armed with this knowledge, we can confidently pierce the veil of uncertainty surrounding map memory allocation in Go.
The above is the detailed content of How Much Memory Does an Initially Empty Go Map Allocate?. For more information, please follow other related articles on the PHP Chinese website!