Avoid deallocate empty arrays?

H. S. Teoh hsteoh at quickfur.ath.cx
Thu Dec 17 22:57:17 UTC 2020


On Thu, Dec 17, 2020 at 06:57:08PM +0000, IGotD- via Digitalmars-d-learn wrote:
[...]
> How does this connect to the array with zero elements? According to
> your explanation if I have understood it correctly, capacity is also
> indicating if the pointer has been "borrowed" from another array
> forcing an allocation whenever the array is modified. However, if
> capacity is zero when the array length is zero, then you would get a
> allocation as well, regardless if there was a previous allocated
> array.

Technically if the array/slice has zero length and zero capacity, it
doesn't have any allocated memory associated with it, so it makes sense
to allocate when you next append to it.  If .ptr is set, though, you
could use .assumeSafeAppend and it should reuse whatever .ptr is
pointing to.

This isn't any different from the slice case of non-zero length. If I
hand you a zero-length slice of my array, I'd be unhappy if you could
use that zero-length slice to modify the other elements in my array. So
it seems logical to set capacity to 0 when array length is reduced to
zero.  When this is not desired, .assumeSafeAppend is the ticket.


On a side note, though, I find this idiosyncratic behaviour annoying
when all I really want is to use an array as, e.g., a backing for a
stack.  For those cases, I ignore array capacity and keep a slice over
the entire allocated storage, including elements that have been erased,
and keep a separate index that represents the logical end-of-array.
While .assumeSafeAppend does work well, it does represent a druntime
function call, which introduces a slight runtime overhead, and it does
come with a slight performace hit.


T

-- 
I am a consultant. My job is to make your job redundant. -- Mr Tom


More information about the Digitalmars-d-learn mailing list