golang slice性能分析

golang在gc这块的做得比较弱,频繁地申请和释放内存会消耗很多的资源。另外slice使用数组实现,有一个容量和长度的问题,当slice的容量用完再继续添加元素时需要扩容,而这个扩容会把申请新的空间,把老的内容复制到新的空间,这是一个非常耗时的操作。有两种方式可以减少这个问题带来的性能开销:

  1. 在slice初始化的时候设置capacity(但更多的时候我们可能并不知道capacity的大小)
  2. 复用slice

下面就针对这两个优化设计了如下的benchmark,代码在: https://github.com/hatlonely/hellogolang/blob/master/internal/buildin/slice_test.go

  1. BenchmarkAppendWithoutCapacity-8 100 21442390 ns/op
  2. BenchmarkAppendWithCapLessLen10th-8 100 18579700 ns/op
  3. BenchmarkAppendWithCapLessLen3th-8 100 13867060 ns/op
  4. BenchmarkAppendWithCapEqualLen-8 200 6287940 ns/op
  5. BenchmarkAppendWithCapGreaterLen10th-8 100 18692880 ns/op
  6. BenchmarkAppendWithoutCapacityReuse-8 300 5014320 ns/op
  7. BenchmarkAppendWithCapEqualLenReuse-8 300 4821420 ns/op
  8. BenchmarkAppendWithCapGreaterLen10thReuse-8 300 4903230 ns/op

主要结论:

  1. 在已知 capacity 的情况下,直接设置 capacity 减少内存的重新分配,有效提高性能
  2. capacity < length,capacity越接近length,性能越好
  3. capacity > lenght,如果太大,反而会造成性能下降,这里当capacity > 10 * length时,与不设置capacity的性能差不太多
  4. 多次使用复用同一块内存能有效提高性能

转载请注明出处 
本文链接:http://hatlonely.github.io/2018/01/18/golang slice性能分析/

posted @ 2018-01-23 14:23  hatlonely  阅读(219)  评论(0编辑  收藏  举报