英文:
Does Go language use Copy-on-write for strings
问题
Go语言是否像Java一样对字符串使用写时复制(Copy-on-write)?即,如果我将一个字符串按值传递给一个方法,并且从不更改它,那么这会分配内存并复制字符串(这将是时间效率低下的),还是只会引用单个副本。
英文:
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.
答案1
得分: 22
这不是写时复制,因为字符串是不可变的。但是共享一个字符串也不会复制底层的内存区域。在Go中,字符串被表示为(长度,数据)对。如果你传递一个字符串,Go会复制长度和指针,但不会复制指向的数据。
更多信息,请参见golang-nuts上的最新讨论。
英文:
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.
For further information, see this recent thread on golang-nuts.
答案2
得分: 1
Go类型string
在实际上等同于java.lang.String
。这两个实现(在Go运行时和JVM中)也是相似的,尽管它们并不完全相同。在传递参数给函数和方法方面,Go字符串的性能与Java字符串相似。
英文:
Go type <code>string</code> is practically equivalent to <code>java.lang.String</code>. The two implementations (in the Go runtime, in the JVM) are similar as well, although they are not identical. In terms of passing arguments to functions and methods, performance of Go strings is similar to Java strings.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论