Thread overview
Zapping a dynamic string
Jul 04, 2023
Cecil Ward
Jul 04, 2023
Cecil Ward
Jul 04, 2023
Cecil Ward
July 04, 2023
I have a mutable dynamic array of dchar, grown by successively appending more and more. When I wish to zap it and hand the contents to the GC to be cleaned up, what should I do? What happens if I set the .length to zero?
July 04, 2023
On Tuesday, 4 July 2023 at 17:01:42 UTC, Cecil Ward wrote:
> I have a mutable dynamic array of dchar, grown by successively appending more and more. When I wish to zap it and hand the contents to the GC to be cleaned up, what should I do? What happens if I set the .length to zero?

I do want to restart the .length at zero in any case as I’m going to begin the appending afresh, so I wish to restart from nothing.
July 04, 2023

On 7/4/23 1:01 PM, Cecil Ward wrote:

>

I have a mutable dynamic array of dchar, grown by successively appending more and more. When I wish to zap it and hand the contents to the GC to be cleaned up, what should I do? What happens if I set the .length to zero?

If you want to forget it so the GC can clean it up, set it to null. If you set the length to 0, the array reference is still pointing at it.

If you want to reuse it (and are sure that no other things are referring to it), you can do:

arr.length = 0;
arr.assumeSafeAppend;

Now, appending to the array will reuse the already-allocated buffer space. Obviously, if you have data in there that is still used, you don't want to use this option.

-Steve

July 04, 2023
On Tuesday, 4 July 2023 at 17:46:22 UTC, Steven Schveighoffer wrote:
> On 7/4/23 1:01 PM, Cecil Ward wrote:
>> I have a mutable dynamic array of dchar, grown by successively appending more and more. When I wish to zap it and hand the contents to the GC to be cleaned up, what should I do? What happens if I set the .length to zero?
>
> If you want to forget it so the GC can clean it up, set it to `null`. If you set the length to 0, the array reference is still pointing at it.
>
> If you want to reuse it (and are sure that no other things are referring to it), you can do:
>
> ```d
> arr.length = 0;
> arr.assumeSafeAppend;
> ```
>
> Now, appending to the array will reuse the already-allocated buffer space. Obviously, if you have data in there that is still used, you don't want to use this option.
>
> -Steve

Many many thanks for that tip, Steve!