本书未发布

Go问题思考

未匹配的标注

问题1: Go可以使用单例模式去初始化一些对象,而不用每次在用的时候都new。按理说这样可以减少Go回收,那为什么在实际项目中看到的都是new对象去用呢?

这里讨论的就是Golang对象的回收机制了。如果是小对象,

问题2: Go append性能问题,如何优化?

// The append built-in function appends elements to the end of a slice. If
// it has sufficient capacity, the destination is resliced to accommodate the
// new elements. If it does not, a new underlying array will be allocated.
// Append returns the updated slice. It is therefore necessary to store the
// result of append, often in the variable holding the slice itself:
// slice = append(slice, elem1, elem2)
// slice = append(slice, anotherSlice...)
// As a special case, it is legal to append a string to a byte slice, like this:
// slice = append([]byte("hello "), "world"...)
func append(slice []Type, elems ...Type) []Type

如果切片的容量够,则不需要扩展。如果不够则会申请新的空间用于扩展,并且返回新的slice。如果频繁去扩展slice,那么性能会造成影响。
怎么优化呢?尽量避免slice的扩展。而且还能减少GC。
一种解决方案:

var slices []int
slices = make([]int, 0, 10)
slices = slices[0:0]

本文章首发在 LearnKu.com 网站上。

上一篇 下一篇
讨论数量: 0
发起讨论 只看当前版本


暂无话题~