This is a creation in Article, where the information may have evolved or changed.
Golang in the GC this block is relatively weak, frequent application and release of memory will consume a lot of resources. In addition, slice uses an array implementation, there is a problem of capacity and length, when the capacity of slice to continue to add elements need to expand, and this expansion will apply for new space, the old content copied into the new space, this is a very time-consuming operation. There are two ways to reduce the performance overhead of this problem:
- Set capacity when slice is initialized (but more often we may not know the size of capacity)
- Multiplexing Slice
The following for these two optimizations designed the following benchmark, code in: https://github.com/hatlonely/...
BenchmarkAppendWithoutCapacity-8 100 21442390 ns/opBenchmarkAppendWithCapLessLen10th-8 100 18579700 ns/opBenchmarkAppendWithCapLessLen3th-8 100 13867060 ns/opBenchmarkAppendWithCapEqualLen-8 200 6287940 ns/opBenchmarkAppendWithCapGreaterLen10th-8 100 18692880 ns/opBenchmarkAppendWithoutCapacityReuse-8 300 5014320 ns/opBenchmarkAppendWithCapEqualLenReuse-8 300 4821420 ns/opBenchmarkAppendWithCapGreaterLen10thReuse-8 300 4903230 ns/op
Main conclusions:
- In the case of known capacity, the direct setting of capacity reduces the reallocation of memory, effectively improving performance
- Capacity < length,capacity closer to length, better performance
- Capacity > Lenght, if too big, but will cause performance degradation, here when capacity > length, and do not set capacity performance is not too much
- Multiple uses of the same block of memory can effectively improve performance
Reprint please indicate the source
This article link: http://hatlonely.github.io/20 ...