Home >Backend Development >Golang >Why Does String Length Seem to Have No Impact on Memory Usage in Go's `map[string]string`?
When optimizing code using a map[string]string with only two possible values ("A" or "B"), reducing it to a map[string]bool seems like an obvious improvement for performance. However, testing reveals a surprising observation: the memory usage of a long string ("a2") is no different from a single-character string ("a").
To understand this behavior, it's important to note that unsafe.Sizeof() does not consider the size of referenced data structures. Instead, it only reports the "shallow" size of the passed value.
In Go, maps are pointers to a data structure. Calling unsafe.Sizeof(somemap) returns the size of this pointer, not the actual memory used by the elements within the map.
Similarly, strings in Go are represented by headers that contain a pointer and a length. Calling unsafe.Sizeof(somestring) will return the size of this header, which is independent of the string's length.
The actual memory required to store a string value in memory is equal to the length of its UTF-8 encoded byte sequence plus the size of its header. To calculate this, you can use the following formula:
stringSize = len(str) + int(unsafe.Sizeof(str))
It's also important to remember that string slicing creates a new header pointing to the backing array of the original string. This means that even if the sliced string (s2) is small, the entire backing array of the original string (s) will still be retained in memory.
The above is the detailed content of Why Does String Length Seem to Have No Impact on Memory Usage in Go's `map[string]string`?. For more information, please follow other related articles on the PHP Chinese website!