Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

This would reallocate, wouldn't it?


If you were using append, then yes. Minor nit: when allocating with length (make(type, len)), you’ll get a slice with zero values for n elements.

If you use make(type, len, capacity), then it would only reallocate if your estimated size was under the actual size.

Also I believe that re-slicing would still use the same underlying array, so it would set the length but still keep the capacity.

You’d have to create a new slice of actual capacity and copy to it.


Neither approach will reallocate.

In the append case, since the underlying slice has capacity, then each append will just extend the length. If estimated length was too small, then reallocation would occur.

In the reslice case, the new slice is a value type that points to the original underlying memory, with a length that is shorter. So no reallocation.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: