Go语言是否对字符串使用写时复制(Copy-on-write)技术?

huangapple go评论76阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2011年12月16日 17:26:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/8532127.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定