问题描述

我正在使用 map [string] string 优化代码,其中地图的值仅为"A"或"B".因此,我认为显然 map [string] bool 会更好,因为地图可容纳约5000万个元素.

I was optimising a code using a map[string]string where the value of the map was only either "A" or "B". So I thought Obviously a map[string]bool was way better as the map hold around 50 millions elements.

var a = "a"
var a2 = "Why This ultra long string take the same amount of space in memory as 'a'"
var b = true
var c map[string]string
var d map[string]bool

c["t"] = "A"
d["t"] = true

fmt.Printf("a: %T, %d\n", a, unsafe.Sizeof(a))
fmt.Printf("a2: %T, %d\n", a2, unsafe.Sizeof(a2))
fmt.Printf("b: %T, %d\n", b, unsafe.Sizeof(b))
fmt.Printf("c: %T, %d\n", c, unsafe.Sizeof(c))
fmt.Printf("d: %T, %d\n", d, unsafe.Sizeof(d))
fmt.Printf("c: %T, %d\n", c, unsafe.Sizeof(c["t"]))
fmt.Printf("d: %T, %d\n", d, unsafe.Sizeof(d["t"]))

结果是:

a: string, 8
a2: string, 8
b: bool, 1
c: map[string]string, 4
d: map[string]bool, 4
c2: map[string]string, 8
d2: map[string]bool, 1

在测试时,我发现有些奇怪,为什么具有很长字符串的 a2 使用8个字节,与 a 只有一个字母一样?

While testing I found something weird, why a2 with a really long string use 8 bytes, same as a wich has only one letter ?

推荐答案

unsafe.Sizeof()
unsafe.Sizeof()

大小不包括x可能引用的任何内存.例如,如果x是切片,则Sizeof返回切片描述符的大小,而不是切片所引用的内存的大小

The size does not include any memory possibly referenced by x. For instance, if x is a slice, Sizeof returns the size of the slice descriptor, not the size of the memory referenced by the slice.

unsafe.Sizeof(somemap)
unsafe.Sizeof(somemap)
reflect.StringHeader
reflect.StringHeader
type StringHeader struct {
        Data uintptr
        Len  int
}
unsafe.Sizeof(somestring)stringLen
unsafe.Sizeof(somestring)stringLen

要获取地图的实际内存需求(深度"),请参见如何在Golang中获取变量的内存大小?

To get the actual memory requirement of a map ("deeply"), see How much memory do golang maps reserve? and also How to get memory size of variable in Golang?

stringlen()stringstring
stringlen()stringstring
var str string = "some string"

stringSize := len(str) + unsafe.Sizeof(str)
string
string

例如:

s := "some loooooooong string"
s2 := s[:2]
s2len(s2) + unsafe.Sizeof(str) = 2 + unsafe.Sizeof(str)s
s2len(s2) + unsafe.Sizeof(str) = 2 + unsafe.Sizeof(str)s

这篇关于Golang中的字符串内存使用情况的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!