4

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
  • 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.
    – newacct
    Dec 16, 2011 at 11:38

2 Answers 2

21

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.

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.
    – Mox
    Aug 10, 2019 at 6:38
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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.