golang slice性能分析

hatlonely ·
大对象用指针,这样复制效率高一些
#1
更多评论
capacity太大内存初始化也需要花费不少时间,如何合理设置capacity是一个问题,太小会产生复制,太大又浪费。 下面是手动从堆中申请内存和释放,对比测试了一下刚觉GO的内存管理做的很不错了(短时间大量内存申请GC可能有问题)。 ``` BenchmarkAppendWithCapEqualLenNoGC-4 1000 11152352 ns/op 128 B/op 5 allocs/op BenchmarkAppendWithCapEqualLen-4 1000 8926832 ns/op 24002564 B/op 1 allocs/op ``` ```go package testslice import ( "testing" "unsafe" "github.com/glycerine/offheap" ) var N = 3000000 var intSize = (32 << (^uint(0) >> 63)) / 8 func BenchmarkAppendWithCapEqualLenNoGC(b *testing.B) { for i := 0; i < b.N; i++ { var arr []int mmap := offheap.Malloc(int64(N*intSize), "") ptrs := (*[3]uintptr)(unsafe.Pointer(&arr)) ptrs[0] = (uintptr)(unsafe.Pointer(&mmap.Mem[0])) *(*int)(unsafe.Pointer(&ptrs[1])) = N *(*int)(unsafe.Pointer(&ptrs[2])) = N for i := 0; i < N; i++ { arr[i] = i } mmap.Free() } } func BenchmarkAppendWithCapEqualLen(b *testing.B) { for i := 0; i < b.N; i++ { arr := make([]int, N, N) for i := 0; i < N; i++ { arr[i] = i } } } ```
#2