Home > Software engineering >  Memory footprint of []int16 vs []int64
Memory footprint of []int16 vs []int64

Time:08-06

Will a slice of int16 take less RAM than int64? Or []int16 will allocate []int64 on a 64-bit machine anyway.

CodePudding user response:

Slices are references to underlying array storage.

A slice of int16 may only reference an array of int16. It may not reference an array of int64 or any other type.

The correct question is then, does an array of int16 have a smaller size than an array of int64 with the same length?

In my experience in practice, yes. I'm not aware of any counter example. Still, I'm not aware of any language rule that actually guarantees it to be so. If you want to test it for yourself in your own environment, it is trivial to do so:

package main

import (
    "fmt"
    "unsafe"
)

func main() {
    fmt.Println(unsafe.Sizeof([10]int16{}))
    fmt.Println(unsafe.Sizeof([10]int64{}))
}
  •  Tags:  
  • go
  • Related