DEV Community

Cover image for A closer look at Go's append function

A closer look at Go's append function

Andy Haskell on July 20, 2019

Appending items onto arrays and array-like objects is common in many programming languages, with functions like JavaScript's Array.push and Python'...
Collapse
 
begmaroman profile image
Roman Behma

The capacity doesn't always double. When it's grown to ~1024 (depends on OS) there applies another logic to increase the capacity of a slice.

Collapse
 
init profile image
Alexander Bykov

This behavior changed in go 1.18 to more smooth allocation:
starting cap growth factor
256 2.0
512 1.63
1024 1.44
2048 1.35
4096 1.30

commit:
github.com/golang/go/commit/2dda92...

Collapse
 
andyhaskell profile image
Andy Haskell

Thanks for the feedback! Will update the post with that info

Collapse
 
larrydwp profile image
larrydwp • Edited

Thanks @andyhaskell Nice write up.

One question about printing the address part:

fmt.Sprintf("%p", slice)
Enter fullscreen mode Exit fullscreen mode

does it print out the address of slice header or the underlying array?