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 +
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With