How are Go type method sets allocated in memory? -


c++ avoids allocating memory class methods every time instance created. gut feeling assume go mitigates kind of duplication. confirm, go store method set of custom struct once?

type custom struct {     value string }  func (c custom) turnitup() {     c.value = "up" }  func (c custom) turnitdown() {     c.value = "down" }  ... // many more methods defined custom.      // (positive , negative directions in 100 dimensions)  func main() {     var many []custom     fmt.println("memory: ", foo.memory()) // measure memory used.     := 0; < 10000; i++ {         append(many, custom{value: "nowhere"})     }      fmt.println("memory: ", foo.memory()) // measure memory used.  } 

the runtime allocates itable when concrete type assigned interface type. itable concrete type , interface type cached , used on later assignments.

as example, code allocate 1 itable:

type volume interface {     turnitup()     turnitdown() } var many []volume := 0; < 10000; i++ {     many = append(many, custom{value: "nowhere"}) } 

and code allocate 2 itables, 1 (custom, upper) , 1 (custom, downer):

type upper interface {     turnitup() } type downer interface {     turnitdown() } var uppers []upper var downers []downer := 0; < 10000; i++ {     uppers = append(uppers, custom{value: "nowhere"})     downers = append(downers, custom{value: "nowhere"}) } 

because example in question not assign custom value interface, no itables created.

the runtime uses static metadata data construct itables. static data allocated , initialized once.

see go data structures: interfaces more details.


Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

Rendering JButton to get the JCheckBox behavior in a JTable by using images does not update my table -