www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Zapping a dynamic string

reply Cecil Ward <cecil cecilward.com> writes:
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?
Jul 04 2023
next sibling parent Cecil Ward <cecil cecilward.com> writes:
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.
Jul 04 2023
prev sibling parent reply Steven Schveighoffer <schveiguy gmail.com> writes:
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
Jul 04 2023
parent Cecil Ward <cecil cecilward.com> writes:
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!
Jul 04 2023