Big O of append in Golang

This all depends on the actual implementation used, but I’m basing this on the standard Go as well as gccgo.

Slices

Reslicing means changing an integer in a struct (a slice is a struct with three fields: length, capacity and pointer to backing memory).

If the slice does not have sufficient capacity, append will need to allocate new memory and copy the old one over. For slices with <1024 elements, it will double the capacity, for slices with >1024 elements it will increase it by factor 1.25.

Strings

Since strings are immutable, each string concatenation with + will create a new string, which means copying the old one. So if you’re doing it N times in a loop, you will allocate N strings and copy memory around N times.

Leave a Comment