Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Big O of append in Golang

What is the complexity of Go's builtin append function? What about string concatenation using +?

I'd like to remove an element from a slice by appending two slices excluding that element, ex. http://play.golang.org/p/RIR5fXq-Sf

nums := []int{0, 1, 2, 3, 4, 5, 6, 7}
fmt.Println(append(nums[:4], nums[5:]...))

=> [0 1 2 3 5 6 7]

http://golang.org/pkg/builtin/#append says that if the destination has sufficient capacity, then that slice is resliced. I'm hoping that "reslicing" is a constant time operation. I'm also hoping the same applies to string concatenation using +.

like image 623
Kaleidoscope Avatar asked Jun 26 '13 23:06

Kaleidoscope


1 Answers

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.

like image 175
Dominik Honnef Avatar answered Oct 21 '22 08:10

Dominik Honnef