本书未发布
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]