Sep 9, 2018 · 1 min read
I think this is incorrect in two ways. Firstly the allocation doesn’t happen each loop, because the capacity is increased by more than one element (for small slices it doubles each time… the number of re-allocations is logarithmic in the final length). Secondly by reassigning the slice as in
result = append(result, item)
the previous array becomes unreachable and can be released. Here is an example:
https://play.golang.org/p/-qp8eQ0CF54
The behavior is similar to that of std::vector in C++ or ArrayList in Java.