"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How does Go\'s Slice Enlargement Algorithm Work?

How does Go\'s Slice Enlargement Algorithm Work?

Posted on 2025-03-22
Browse:515

How does Go\'s Slice Enlargement Algorithm Work?

Go Slice Enlargement Algorithm

When appending elements to a slice, it may need to expand its capacity. The specific algorithm used for this enlargement is not explicitly defined in the Go specifications.

Code Implementation

The code responsible for resizing slices in the append operation can be found in the Go source code repository:

https://github.com/golang/go/blob/master/src/runtime/slice.go

Enlargement Rules

As of 2014-2020, the implemented rules are:

  1. Step-by-Step Doubling: If adding elements to the slice will increase its length by more than double its original length, the new capacity is set directly to the new length.
  2. Incremental Doubling: For lengths less than 1024, the capacity is doubled until it is sufficient. For lengths larger than 1024, the capacity is increased by 25% each iteration.

Capacity Doubling

No, the capacity is not always doubled when enlarging a slice.

The strategies described above may result in varying increases in capacity depending on the original slice length. Additionally, these heuristics are subject to change in future Go versions, so it's recommended to consult the latest implementation for the most up-to-date information.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3