go语言调用append之后是否重新分配内存?
查看tidb源代码:::util/charset/charset.go,下面有段代码:
// GetAllCharsets gets all charset descriptions in the local charsets. func GetAllCharsets() []*Desc { descs := make([]*Desc, 0, len(charsets)) // The charsetInfos is an array, so the iterate order will be stable. for _, ci := range charsetInfos { c, ok := charsets[ci.Name] if !ok { continue } desc := &Desc{ Name: c.Name, DefaultCollation: c.DefaultCollation.Name, Desc: c.Desc, Maxlen: c.Maxlen, } descs = append(descs, desc) } return descs }
查看append,思考一个问题,调用本方法之后,descs内存地址是否重新分配?
特做如下例子进行测试:
type Names struct { Name string }
mynames := make([]*Names, 0) for i := 0; i < 10; i++ { my := &Names{ Name: "append"} mynames = append(mynames, my) fmt.Println(&mynames) }
运行结果如下:
从10次的输出结果来看,调用append内部函数,不改变内存地址,也就是不产生性能损耗。