On Tue, Jun 4, 2013 at 2:42 AM, beevik <
br...@beevik.com> wrote:
> Go gives us the built-in copy function to make a copy of a slice's contents,
> but it doesn't (to my knowledge) offer anything similar for strings. This
> means that in order to copy a substring (and thereby allow the larger string
> to be released by the garbage collector once it is no longer referenced),
> you have to copy the substring to a byte slice and then back to a string.
> This seems less than optimal. It's also kind of ugly.
>
> Is there a faster way to "deep copy" a string that doesn't require
> conversion to and from a slice first? Wouldn't a built-in copy function
> that accepts a destination string be useful in this regard?
You can do this with reflect and unsafe, but I think a better solution
would be for the compiler to recognize code like string([]byte(s)) and
optimize it to a single copy operation. Right now, the version below
is about 2x faster:
func Copy(s string) string {
var b []byte
h := (*reflect.SliceHeader)(unsafe.Pointer(&b))
h.Data = (*reflect.StringHeader)(unsafe.Pointer(&s)).Data
h.Len = len(s)
h.Cap = len(s)
return string(b)
}