Big O of append in Golang

前端 未结 1 1560
心在旅途
心在旅途 2020-12-07 00:50

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

I\'d like to remove an element from a sli

相关标签:
1条回答
  • 2020-12-07 01:23

    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.

    0 讨论(0)
提交回复
热议问题