drghhp8706 2015-07-14 03:26
浏览 12
已采纳

Go类型方法集如何在内存中分配?

C++ avoids allocating memory for class methods every time an instance is created. My gut feeling is to assume that Go also mitigates this kind of duplication. Just to confirm, does Go store the method set of a custom struct only once?

type Custom struct {
    value string
}

func (c Custom) TurnItUp() {
    c.value = "up"
}

func (c Custom) TurnItDown() {
    c.value = "down"
}

... // Many more methods defined for Custom. 
    // (Positive and negative directions in 100 dimensions)

func main() {
    var many []Custom
    fmt.Println("Memory: ", foo.memory()) // Measure memory used.
    for i := 0; i < 10000; i++ {
        append(many, Custom{value: "nowhere"})
    } 
    fmt.Println("Memory: ", foo.memory()) // Measure memory used. 
}
  • 写回答

2条回答 默认 最新

  • duandui5648 2015-07-14 04:13
    关注

    The runtime allocates an itable when a concrete type is assigned to an interface type. The itable for the concrete type and interface type is cached and used on later assignments.

    As an example, this code will allocate one itable:

    type Volume interface {
        TurnItUp()
        TurnItDown()
    }
    var many []Volume
    for i := 0; i < 10000; i++ {
        many = append(many, Custom{value: "nowhere"})
    }
    

    and this code will allocate two itables, one for (Custom, Upper) and one for (Custom, Downer):

    type Upper interface {
        TurnItUp()
    }
    type Downer interface {
        TurnItDown()
    }
    var uppers []Upper
    var downers []Downer
    for i := 0; i < 10000; i++ {
        uppers = append(uppers, Custom{value: "nowhere"})
        downers = append(downers, Custom{value: "nowhere"})
    }
    

    Because the example in the question does not assign a Custom value to an interface, no itables are created.

    The runtime uses static metadata data to construct itables. The static data is allocated and initialized once.

    See Go Data Structures: Interfaces for more details.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?