Does Go language use Copy-on-write for strings [duplicate]
Asked Answered
B

2

5

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.

Briton answered 16/12, 2011 at 9:26 Comment(1)
"copy-on-write ... as in Java" makes no sense. Objects are not values in Java; only references are. And passing a reference NEVER makes a copy of the object it points to under any circumstances. Passing or assigning a reference always will refer to the same object as the original reference. An object is never copied (not "on-write"), unless you explicitly copy it through some method, and get a reference to a new object back.Metalinguistic
A
22

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.

Arterial answered 16/12, 2011 at 10:18 Comment(1)
If it is not a copy on write, then what will happen in this scenario? e.g. s := "hello"; t := s; s += " world"; t += " there". one of these have to create a copy, probably t in this case.Amazement
B
1

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.

Butler answered 16/12, 2011 at 13:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.