从 string
转换为 []byte
是否分配了新内存?此外,从 []byte
转换为 string
是否会分配新内存?
s := "a very long string"
b := []byte(s) // does this doubled the memory requirement?
b := []byte{1,2,3,4,5, ...very long bytes..}
s := string(b) // does this doubled the memory requirement?
最佳答案
在这两种情况下都是。
String types是不可变的。因此将它们转换为可变的 slice type将分配一个新的 slice 。另见 http://blog.golang.org/go-slices-usage-and-internals
反之亦然。否则改变 slice 会改变字符串,这将与规范相矛盾。
关于memory-management - Golang 中 []byte 和 string 转换的技术问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27293131/