There are places throughout the standard packages where extra copies happen 
due to []byte <-> string conversion (like strings.Join(), 
os.*File.WriteString() etc.)   I am assuming they don't use an unsafe-magic 
way to make aliasing strings and []bytes because they don't want people to 
shoot themselves in the foot.

As it is, I do my best to stick with []byte to avoid the copies.


On Monday, July 11, 2016 at 8:28:51 AM UTC-5, Ian Lance Taylor wrote:
>
> On Mon, Jul 11, 2016 at 3:49 AM, Manlio Perillo 
> <manlio....@gmail.com <javascript:>> wrote: 
> > Il giorno domenica 10 luglio 2016 04:51:21 UTC+2, Ian Lance Taylor ha 
> > scritto: 
> >> 
> >> On Sat, Jul 9, 2016 at 4:38 PM, Erich Rickheit KSC <rick...@numachi.com> 
>
> >> wrote: 
> >> > I found myself writing code like this: 
> >> > 
> >> >         s := make([]byte, len) 
> >> >         for i := 0; i < len; i++ { 
> >> >                 // fill in s with stringy goodness 
> >> >         } 
> >> >         return string(s) 
> >> > 
> >> > Does this reuse the memory in s for the string, or does it allocate 
> new 
> >> > memory and copy? Or does escape analysis swoop in and make that 
> >> > decision? 
> >> 
> >> This will normally allocate new memory for the string and copy over 
> >> the bytes.  I believe that the compiler could optimize this case, but 
> >> as far as I know no Go compiler currently implements that 
> >> optimization. 
> >> 
> > 
> > Since the compiler can already tell that s does not escape the function, 
> > what is the additional complexity for this optimization? 
>
> Making sure that s is not modified after the conversion to string. 
> That could happen in fairly subtle ways even if the slice is known to 
> not escape, as in 
>     s2 := append(s, 0) 
>     str := string(s) 
>     s2[0] = 1 
>
> Ian 
>

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to