This is a weird corner case in string concatenation optimization. runtime.concatstrings (what the + in this code gets rewritten to) has an optimization where if all the strings but one that it is concatenating are 0 length, then it returns the remaining one without doing any allocation. Because of that optimization, runtime.concatstrings might return its argument. Thus, we can't do the zero-copy conversion of []byte to string for arguments to runtime.concatstrings. Except when we know that at least one of the input strings has non-zero length. Then we can. That's what is happening in f2.
On Monday, April 17, 2017 at 11:06:26 PM UTC-7, T L wrote: > > > package main > > import "fmt" > import "testing" > > var s string > var a = make([]byte, 1000) > > func f0() { > x := string(a) > s = x + x + x + > x + x + x + > x + x + x + > x > } > > func f1() { > s = string(a) + string(a) + string(a) + > string(a) + string(a) + string(a) + > string(a) + string(a) + string(a) + > string(a) > } > > func f2() { > s = (" " + > string(a) + string(a) + string(a) + > string(a) + string(a) + string(a) + > string(a) + string(a) + string(a) + > string(a) )[1:] > } > > func main() { > fmt.Println(testing.AllocsPerRun(1, f0)) // 2 > fmt.Println(testing.AllocsPerRun(1, f1)) // 11 > fmt.Println(testing.AllocsPerRun(1, f2)) // 1 > } > > why doesn't gc make optimization for f1? > -- 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.