Go语言是否使用字符串写时复制 [英] Does Go language use Copy-on-write for strings
问题描述
Go语言是否像Java中那样对字符串使用写时复制?IE.如果我按值将字符串传递给方法而从未更改,则它将分配内存并复制字符串(这将节省时间),或者仅引用单个副本.
Does Go language use Copy-on-write for strings as in Java? I.e. if I pass a string by value to a method and never change it will this allocate memory and copy the string (which will be time inefficient) or it will just reference a single copy.
推荐答案
它不是写时复制的,因为字符串是不可变的.但是共享一个字符串也不会复制基础内存区域.在Go中,字符串表示为(长度,数据)对.如果传递字符串,Go将复制长度和指针,但不复制所指向的数据.
It's not Copy-on-Write, as strings are immutable. But sharing a string will not make a copy of the underlying memory region either. In Go, a string is represented as a (length, data) pair. If you pass a string around, Go will copy the length and the pointer but not the data pointed to.
有关更多信息,请参见有关golang-nuts的最新主题.
For further information, see this recent thread on golang-nuts.
这篇关于Go语言是否使用字符串写时复制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!