英文:
Technical things about conversion from []byte and string in Golang
问题
将string
转换为[]byte
会分配新的内存吗?同样,将[]byte
转换为string
会分配新的内存吗?
s := "一个非常长的字符串"
b := []byte(s) // 这会使内存需求翻倍吗?
b := []byte{1,2,3,4,5, ...非常长的字节..}
s := string(b) // 这会使内存需求翻倍吗?
英文:
Is it true that converting from string
to []byte
allocates new memory? Also, does converting from []byte
to string
allocates new memory?
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?
答案1
得分: 5
是的,在这两种情况下都是如此。
字符串类型 是不可变的。因此,将它们转换为可变的 切片类型 将会分配一个新的切片。参见 http://blog.golang.org/go-slices-usage-and-internals
反之亦然。否则,修改切片将会改变字符串,这将与规范相矛盾。
英文:
Yes in both cases.
String types are immutable. Therefore converting them to a mutable slice type will allocate a new slice. See also http://blog.golang.org/go-slices-usage-and-internals
The same with the inverse. Otherwise mutating the slice would change the string, which would contradict the spec.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论