[]int16和[]int64的内存占用情况

huangapple go评论75阅读模式
英文:

Memory footprint of []int16 vs []int64

问题

int16类型的切片在内存中占用的空间是否比int64类型的切片少?或者在64位机器上,[]int16类型的切片是否会分配[]int64类型的切片?

英文:

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

答案1

得分: 2

切片是对底层数组存储的引用。

int16 类型的切片只能引用 int16 类型的数组,不能引用 int64 或其他类型的数组。

正确的问题是,长度相同的 int16 数组是否比 int64 数组更小?

根据我的实际经验,是的。我不知道任何反例。然而,我也不知道任何实际保证它是如此的语言规则。如果你想在自己的环境中测试它,这很容易做到:

package main

import (
	"fmt"
	"unsafe"
)

func main() {
	fmt.Println(unsafe.Sizeof([10]int16{}))
	fmt.Println(unsafe.Sizeof([10]int64{}))
}
英文:

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

huangapple
  • 本文由 发表于 2022年8月6日 05:00:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/73255232.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定