内存警察
警惕一切隐式内存分配
典型case:
函数返回了字符串、切片,警惕一切字符串
传进去的输入,函数内部重新分配了一个新的内存返回
对象复用
1.sync.pool
保证有一个ch大小的对象可用
假设有cpu核数那么多并发任务,可以保证gc的时候有保底在
2.局部cache
sync.pool毕竟加锁,要本地ctx能挂载临时对象集,那肯定比pool效率高
currAccmulator在for循环之外的一个临时变量
封装在ctx里面的一个临时变量,跟随ctx整个生命周期销毁
storage存储,后续还能复用
slice复用
1.len与cap
func TestD(t *testing.T) {ints := make([]int, 0, 6)ints = append(ints, 6, 6, 6, 6, 6, 6)// The clear built-in function clears maps and slices.// For maps, clear deletes all entries, resulting in an empty map.// For slices, clear sets all elements up to the length of the slice clear(ints)logger.DEBUG("ints", ints, " cap: ", cap(ints), " len:", len(ints))ints = ints[:0] // len == 0, cap == 6 之前的元素还在logger.DEBUG("ints", ints, " cap: ", cap(ints), " len:", len(ints))ints = append(ints[:0], 1, 2, 3) // 这样就覆盖了原来的元素logger.DEBUG("ints", ints, " cap: ", cap(ints), " len:", len(ints))// recapadditionalItems := 10intsLen := len(ints)if n := intsLen + additionalItems - cap(ints); n > 0 {ints = append(ints[:cap(ints)], make([]int, n)...)}ints = ints[:intsLen]// resizesize := 10if cap(ints) > size {ints = ints[:size]} else {ints = make([]int, size)} }
=== RUN TestD 2024/06/13 23:24:27 [DEBUG] ints[0 0 0 0 0 0] cap: 6 len:6 2024/06/13 23:24:27 [DEBUG] ints[] cap: 6 len:0 2024/06/13 23:24:27 [DEBUG] ints[1 2 3] cap: 6 len:3