GoLang-内存分配-[]字节与字符串 [英] GoLang - memory allocation - []byte vs string

查看:111
本文介绍了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数据所需的数据类型,请测试上面的示例代码以了解[]bytestring类型的内存分配.


To decide the datatype needed to receive JSON data from CloudFoundry, am testing above sample code to understand the memory allocation for []byte vs string type.

string类型变量c的预期大小为1个字节x 4个ascii编码字母= 4个字节,但是大小显示为16个字节.

Expected size of string type variable c is 1 byte x 4 ascii encoded letter = 4 bytes, but the size shows 16 bytes.

对于byte类型变量d,GO将字符串作为字符串文字嵌入到可执行程序中.它在运行时使用runtime.stringtoslicebyte函数将字符串文字转换为字节片.像... []byte{102, 111, 111, 108}

For byte type variable d, GO embeds the string in the executable program as a string literal. It converts the string literal to a byte slice at runtime using the runtime.stringtoslicebyte function. Something like... []byte{102, 111, 111, 108}

byte类型变量d的预期大小再次为1个字节x 4个ascii值= 4个字节,但是变量d的大小显示24个字节作为其基础数组容量.

Expected size of byte type variable d is again 1 byte x 4 ascii values = 4 bytes but the size of variable d shows 24 bytes as it's underlying array capacity.

为什么两个变量的大小都不是4个字节?

Why the size of both variables is not 4 bytes?

推荐答案

Go中的切片和字符串都是类似结构的标头:

Both slices and strings in Go are struct-like headers:

reflect.SliceHeader :

type SliceHeader struct {
        Data uintptr
        Len  int
        Cap  int
}

reflect.StringHeader :

type StringHeader struct {
        Data uintptr
        Len  int
}

unsafe.Sizeof() 报告的大小是这些标头的大小,不包括大小指向数组:

The sizes reported by unsafe.Sizeof() are the sizes of these headers, exluding the size of the pointed arrays:

Sizeof接受任何类型的表达式x并返回假设变量v的字节大小,就好像v是通过var v = x声明的一样. 大小不包括x可能引用的任何内存.例如,如果x是切片,则Sizeof返回切片描述符的大小,而不是切片所引用的内存的大小. >

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.

要获取某个任意值的实际(递归")大小,请使用Go的内置测试和基准测试框架.有关详细信息,请参见如何获取Golang中的变量?

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 Golang?

有关字符串的详细信息,请参见 Golang中的字符串内存使用情况. string值所需的完整内存可以这样计算:

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) + unsafe.Sizeof(str)

这篇关于GoLang-内存分配-[]字节与字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆