| ▲ | OptionOfT 2 hours ago | |
> ... > On the third loop iteration, the backing store of size 2 is full. append again has to allocate a new backing store, this time of size 4. The old backing store of size 2 is now garbage. Correct me if I'm wrong, but isn't this a worst-case scenario? realloc can, iirc, extend in place. Your original pointer is still invalid then, but no copy is needed then. Unless I'm missing something? Equally, what happens to the ordering of variables on the stack? Is this new one pushed as the last one? Or is there space kept open? E.g.: | ||
| ▲ | kbolino an hour ago | parent | next [-] | |
The ability to grow without copying is already part of how slices work. Every slice is really a 3-word tuple of pointer, length, and capacity. If not explicitly set with make, the capacity property defaults to a value that fills out the size class of the allocation. It just so happens that, in this case, the size of the Task type doesn't allow for more than 1 value to fit in the smallest allocation. If you were to do this with a []byte or []int32 etc., you would see that the capacity doesn't necessarily start at 1: https://go.dev/play/p/G5cifdChGIZ | ||
| ▲ | an hour ago | parent | prev [-] | |
| [deleted] | ||