Question

When append a slice, the slice may be enlarged if necessary. Because the spec doesn't specify the algorithm, I am curious about it.

I try to find the append implementation in the Go source code, but can't find it.

Could anyone explain the specified algorithm for enlarging slice? Is the capacity always doubled? or Could anyone provide the source code position of append? I can check it myself.

Was it helpful?

Solution

The code responsible for growing slices in append can be found here.

As of 2014-2020 the implemented rules are:

  1. If appending to the slice will increase its length by more than double, the new capacity is set to the new length.
  2. Otherwise, double the capacity if the current length is less than 1024, or by 25% if it is larger. Repeat this step until the new capacity fits the desired length.

Presumably this isn't part of the specification so the heuristics can be changed in future if needed. You can check the most current version of this implementation on the master branch.

OTHER TIPS

In Go 1.18 it changed. https://github.com/golang/go/commit/2dda92ff6f9f07eeb110ecbf0fc2d7a0ddd27f9d

starting cap    growth factor
256             2.0
512             1.63
1024            1.44
2048            1.35
4096            1.30
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top