Performance analysis of Golang slice

Source: Internet
Author: User
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:

    1. Set capacity when slice is initialized (but more often we may not know the size of capacity)
    2. 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:

    1. In the case of known capacity, the direct setting of capacity reduces the reallocation of memory, effectively improving performance
    2. Capacity < length,capacity closer to length, better performance
    3. Capacity > Lenght, if too big, but will cause performance degradation, here when capacity > length, and do not set capacity performance is not too much
    4. 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 ...

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.