This ideally shouldn't happen.

For some reason the compiler is keeping t.y alive across the printMemStat 
calls, even when it only needs to keep t.x alive.
I've opened an issue https://github.com/golang/go/issues/24263

On Monday, March 5, 2018 at 8:08:59 AM UTC-8, di...@veryhaha.com wrote:
>
>
>
> On Monday, March 5, 2018 at 10:34:35 AM UTC-5, Volker Dobler wrote:
>>
>> Your two programs are not the same.
>> Try  fmt.Println(bs[0]) instead of len(bs) in the
>> first one. 
>>
>
>> V.
>>
>
> Yes, you are right.
> They are different.
> Their behaviors should be compile dependent. 
>  
>
>>
>> On Monday, 5 March 2018 16:05:05 UTC+1, di...@veryhaha.com wrote:
>>>
>>> Slice:
>>>
>>> package main
>>>
>>> import "fmt"
>>> import "runtime"
>>>
>>> func printMemStat(gcFirstly bool) {
>>>     if gcFirstly {
>>>         runtime.GC()
>>>     }
>>>     var stat runtime.MemStats
>>>     runtime.ReadMemStats(&stat)
>>>     println(stat.Alloc)
>>> }
>>>
>>> func main() {
>>>     bs := make([]int, 1000000)
>>>     
>>>     printMemStat(false) // about 8071272
>>>     printMemStat(true)  // about 67376
>>>     // looks the underlying bytes has already
>>>     // been garbage collected in the above call.
>>>     
>>>     fmt.Println(len(bs))
>>> }
>>>
>>>
>>> Custom type:
>>>
>>> package main
>>>
>>> import "fmt"
>>> import "runtime"
>>>
>>> type T struct {
>>>     x int
>>>     y *[1000000]int
>>> }
>>>
>>> func printMemStat(gcFirstly bool) {
>>>     if gcFirstly {
>>>         runtime.GC()
>>>     }
>>>     var stat runtime.MemStats
>>>     runtime.ReadMemStats(&stat)
>>>     println(stat.Alloc)
>>> }
>>>
>>> func main() {
>>>     t := T{123, new([1000000]int)}
>>>     
>>>     printMemStat(false) // about 8071576
>>>     printMemStat(true)  // about 8071576
>>>     
>>>     fmt.Println(t.x)
>>> }
>>>
>>

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