drema2014
2019-04-29 13:42
浏览 490
已采纳

GoLang-内存分配-[]字节与字符串

In the below code:

c := "fool"
d := []byte("fool")
fmt.Printf("c: %T, %d
", c, unsafe.Sizeof(c)) // 16 bytes
fmt.Printf("d: %T, %d
", d, unsafe.Sizeof(d)) // 24 bytes

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.


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

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}

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.


Why the size of both variables is not 4 bytes?

图片转代码服务由CSDN问答提供 功能建议

在以下代码中:

  c:=“傻瓜 “ 
d:= [] byte(” fool“)
fmt.Printf(” c:%T,%d 
“,c,unsafe.Sizeof(c))// 16字节
fmt.Printf(” d  :%T,%d 
“,d,unsafe.Sizeof(d))// 24字节
   
 
 

数据类型需要从CloudFoundry接收JSON数据,正在测试上面的示例代码以了解 [] byte string 类型的内存分配。 < hr>

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

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

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


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

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

  • dousonghs58612 2019-04-29 13:56
    最佳回答

    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
    }
    

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

    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)
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题