本文介绍了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:

要获取某个任意值的实际(递归")大小,请使用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-内存分配-[]字节与字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 16:16