string - GoLang - 内存分配 - []字节与字符串
问题描述
在下面的代码中:
c := "fool"
d := []byte("fool")
fmt.Printf("c: %T, %d\n", c, unsafe.Sizeof(c)) // 16 bytes
fmt.Printf("d: %T, %d\n", d, unsafe.Sizeof(d)) // 24 bytes
要确定从 CloudFoundry 接收 JSON 数据所需的数据类型,我正在测试上面的示例代码以了解[]byte
vsstring
类型的内存分配。
string
类型变量的预期大小c
为 1 字节 x 4 ascii 编码字母 = 4 字节,但大小显示为 16 字节。
对于byte
类型 variable d
,GO 将字符串作为字符串文字嵌入到可执行程序中。runtime.stringtoslicebyte
它在运行时使用该函数将字符串文字转换为字节切片。就像是...[]byte{102, 111, 111, 108}
byte
类型变量的预期大小d
再次为 1 字节 x 4 ascii 值 = 4 字节,但变量的大小d
显示为 24 字节,因为它是底层数组容量。
为什么两个变量的大小都不是 4 字节?
解决方案
Both slices and strings in Go are struct-like headers:
type SliceHeader struct {
Data uintptr
Len int
Cap int
}
type StringHeader struct {
Data uintptr
Len int
}
The sizes reported by unsafe.Sizeof()
are the sizes of these headers, exluding the size of the pointed arrays:
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.
To get the actual ("recursive") size of some arbitrary value, use Go's builtin testing and benchmarking framework. For details, see How to get memory size of variable in Go?
For strings specifically, see String memory usage in Golang. The complete memory required by a string
value can be computed like this:
var str string = "some string"
stringSize := len(str) + int(unsafe.Sizeof(str))
推荐阅读
- java - Windows Server 2019 (localhost) 中的 Java 套接字连接被拒绝
- r - 在 R 中使用 poly() 内部与外部 lm() 时的不同行为
- javascript - Meteor:使用来自 autoValue 字段的值来计算另一个 autoValue 字段中的值
- android - 为什么我的按钮将“colorPrimary”作为默认背景颜色?
- python - 如何点击这个,硒
- node.js - Angular 9 Universal SSR 在带有 HTTP 调用的延迟加载路由上失败
- android - WorkManager 定期请求未运行?
- mysql - MySQL服务器版本:插入表时出现Mysql错误
- javascript - 如何用另一个数组更改对象数组的条目
- algorithm - 为什么需要考虑负循环的有向图的最短路径问题?