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.
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.
Go type string
is practically equivalent to java.lang.String
. 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.
来源:https://stackoverflow.com/questions/8532127/does-go-language-use-copy-on-write-for-strings