Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How the slice is enlarged by append? Is the capacity always doubled?

Tags:

go

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.

like image 835
Nan Xiao Avatar asked May 08 '14 02:05

Nan Xiao


People also ask

How do you append to a slice?

Since slices are dynamically-sized, you can append elements to a slice using Golang's built-in append method. The first parameter is the slice itself, while the next parameter(s) can be either one or more of the values to be appended.

Does append create a new slice?

The append built-in function appends elements to the end of a slice. If it has sufficient capacity, the destination is resliced to accommodate the new elements. If it does not, a new underlying array will be allocated. Append returns the updated slice.


1 Answers

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.

like image 120
James Henstridge Avatar answered Oct 23 '22 07:10

James Henstridge