title: How to get memory size of variable in Go?
body: <p>I am curious about the memory cost of <code>map</code> and <code>slice</code>, so I wrote a program to compare the sizes. I get the memory size by <code>unsafe.Sizeof(s)</code>, but obviously it is wrong, because when I change the size, the output is the same.</p>
  
  <pre><code>func getSlice(size int) []int {
      t := time.Now()
      s := make([]int, size*2)
      for i := 0; i &lt; size; i++ {
          index := i &lt;&lt; 1
          s[index] = i
          s[index+1] = i
      }
      fmt.Println("slice time cost: ", time.Since(t))
      return s
  }
  
  func getMap(size int) map[int]int {
      t := time.Now()
      m := make(map[int]int, size)
      for i := 0; i &lt; size; i++ {
          m[i] = i
      }
      fmt.Println("map time cost: ", time.Since(t))
      return m
  }
  
  func TestMem(t *testing.T) {
      size := 1000
      s := getSlice(size)
      m := getMap(size)
      fmt.Printf("slice size: %d\n", unsafe.Sizeof(s))
      fmt.Printf("map size: %d\n", unsafe.Sizeof(m))
  }
  </code></pre>