golang slice性能分析

2018-01-22  本文已影响0人  hatlonely

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

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

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

BenchmarkAppendWithoutCapacity-8                     100      21442390 ns/op
BenchmarkAppendWithCapLessLen10th-8                  100      18579700 ns/op
BenchmarkAppendWithCapLessLen3th-8                   100      13867060 ns/op
BenchmarkAppendWithCapEqualLen-8                     200       6287940 ns/op
BenchmarkAppendWithCapGreaterLen10th-8               100      18692880 ns/op
BenchmarkAppendWithoutCapacityReuse-8                300       5014320 ns/op
BenchmarkAppendWithCapEqualLenReuse-8                300       4821420 ns/op
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%20slice性能分析/

上一篇下一篇

猜你喜欢

热点阅读