切片的内存大小
slice := []int{1,2,3}
fmt.Println(unsafe.Sizeof(slice)) //24
上面声明了一个切片,然后打印出sizeof的值为24,但是不管slice里的元素为多少,sizeof返回的数据都是24。
原因:官方文档解释
Sizeof takes an expression x of any type and returns the size in bytes of a hypothetical variable v as if v was declared via var v = x. The size does not include any memory possibly referenced by x. For instance, if x is a slice, Sizeof returns the size of the slice descriptor, not the size of the memory referenced by the slice.
如果x为一个切片,sizeof返回的大小是切片的描述符,而不是切片所指向的内存的大小。
数组的内存大小
那么这里如果换成一个数组呢?而不是一个切片
arr := [...]int{1,2,3,4,5}
fmt.Println(unsafe.Sizeof(arr)) //40
arr2 := [...]int{1,2,3,4,5,6}
fmt.Println(unsafe.Sizeof(arr)) //48
可以看到sizeof(arr)的值是在随着arr的元素的个数的增加而增加
原因:sizeof总是在编译期就进行求值,而不是在运行时,这意味着,sizeof的返回值可以赋值给常量
字符串内存大小
str := "hello"
fmt.Println(unsafe.Sizeof(str)) //16
不论字符串的len有多大,sizeof始终返回16,这是为啥,字符串不是也是不可变的吗?
- 实际上字符串类型对应一个结构体,该结构体有两个域,第一个域是指向该字符串的指针,第二个域是字符串的长度,每个域占8个字节,但是并不包含指针指向的字符串的内容,这也就是为什么sizeof始终返回的是16 *