Answer the question
In order to leave comments, you need to log in
How much does Struct{}{} take up in memory?
How much storage of such a structure takes in memory, judging by the code below, it doesn’t take it at all, but how is this possible, because somewhere it should be stored that the data type in the map is an empty structure.
code from here
package main
import (
"fmt"
"unsafe"
)
func main() {
variant1 := make(map[string]bool)
variant2 := make(map[string]struct{})
for i := 0; i < 1<<16; i++ {
key := fmt.Sprintf("%v", i)
variant1[key] = true
variant2[key] = struct{}{}
}
size1 := unsafe.Sizeof(variant1)
size2 := unsafe.Sizeof(variant2)
for k, v := range variant1 {
size1 += unsafe.Sizeof(k)
size1 += unsafe.Sizeof(v)
}
for k, v := range variant2 {
size2 += unsafe.Sizeof(k)
size2 += unsafe.Sizeof(v)
}
fmt.Printf("bool variant : %v bytes\n", size1)
fmt.Printf("struct variant: %v bytes\n", size2)
// bool variant : 1114120 bytes
// struct variant: 1048584 bytes
// size1-size2 65536 bytes
}
Answer the question
In order to leave comments, you need to log in
That's right, it takes 0 bytes.
You can check:
package main
import (
"fmt"
"unsafe"
)
type S1 struct {
f1 int
}
func main() {
s1 := S1{}
s2 := struct{}{}
fmt.Printf("s1 size: %v\n", unsafe.Sizeof(s1))
fmt.Printf("s2 size: %v\n", unsafe.Sizeof(s2))
}
s1 size: 8
s2 size: 0
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question