On Friday, April 21, 2017 at 1:33:57 AM UTC+8, Keith Randall wrote:
>
>
>
> On Wednesday, April 19, 2017 at 3:56:21 AM UTC-7, T L wrote:
>>
>>
>>
>> On Wednesday, April 19, 2017 at 3:37:29 AM UTC+8, Keith Randall wrote:
>>>
>>> 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.
>>>
>>  
>> Keith, thanks. But I haven't fully get your explanation.
>> Do you mean that compiler can't confirm whether or not the optimization 
>> which might return its argument can be used for f1 at compile time,
>> but compiler can confirm it can't be used for f2 at compile time?
>>
>> That's correct.  Or more precisely, if that optimization is used in f2, 
> it can only be used for the string " ", it can't be used for any of the 
> string(a) arguments.
>

ok, thanks. 
but I feel the optimization used f2 is more general.
 

>  
>>
>>>
>>> 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.

Reply via email to