Sobes.tech
Middle

What algorithm is used to increase the size of a slice in Go?

sobes.tech AI

Answer from AI

Increasing the size of a slice in Go occurs according to the following algorithm when using the append() function:

  1. The required capacity of the new slice is determined.
  2. If the current capacity is sufficient to hold the new elements (cap(s) >= len(s) + len(elements)), then the elements are simply added to the end of the current underlying array, and the new slice points to this area.
  3. If the current capacity is insufficient, a new underlying array with a larger capacity is allocated. The algorithm for determining the new capacity is as follows:
    • If the required capacity is greater than twice the current capacity (requiredCap > 2 * oldCap), then the new capacity equals the required capacity.
    • If the current capacity is less than 1024 (oldCap < 1024), then the new capacity is doubled (newCap = oldCap * 2).
    • If the current capacity is greater than or equal to 1024 (oldCap >= 1024), then the new capacity increases by 25% (newCap = oldCap + oldCap/4) until it is greater than or equal to the required capacity.
  4. Elements from the old underlying array are copied to the new array.
  5. New elements are added to the end of the new array.
  6. The new capacity may be slightly larger than the calculated value due to memory alignment.
  7. The append() function returns a new slice pointing to the new underlying array.

Meanwhile, the old slice and its underlying array can be garbage collected if there are no more references to them.