C
C
calculator2122021-08-27 16:19:02
go
calculator212, 2021-08-27 16:19:02

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

1 answer(s)
E
Evgeny Mamonov, 2021-08-27
@calculator212

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))
}

Conclusion
s1 size: 8
s2 size: 0

Where only keys are needed in the map - I always make the value struct{}{}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question