Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

go - String memory usage in Golang

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
", a, unsafe.Sizeof(a))
fmt.Printf("a2: %T, %d
", a2, unsafe.Sizeof(a2))
fmt.Printf("b: %T, %d
", b, unsafe.Sizeof(b))
fmt.Printf("c: %T, %d
", c, unsafe.Sizeof(c))
fmt.Printf("d: %T, %d
", d, unsafe.Sizeof(d))
fmt.Printf("c: %T, %d
", c, unsafe.Sizeof(c["t"]))
fmt.Printf("d: %T, %d
", d, unsafe.Sizeof(d["t"]))

And the result was:

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...