length = 0 clears reserve

Jon Degenhardt via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Apr 11 14:06:45 PDT 2017


On Tuesday, 11 April 2017 at 20:00:48 UTC, Jethro wrote:
> On Tuesday, 11 April 2017 at 03:00:29 UTC, Jon Degenhardt wrote:
>> On Tuesday, 11 April 2017 at 01:59:57 UTC, Jonathan M Davis 
>> wrote:
>>> On Tuesday, April 11, 2017 01:42:32 Jethro via 
>>> Digitalmars-d-learn wrote:
>>>> [...]
>>>
>>> You can't reuse the memory of a dynamic array by simply 
>>> setting its length to 0. If that were allowed, it would risk 
>>> allow dynamic arrays to stomp on each others memory (since 
>>> there is no guarantee that there are no other dynamic arrays 
>>> referring to the same memory). However, if you know that 
>>> there are no other dynamic arrays referrin to the same 
>>> memory, then you can call assumeSafeAppend on the dynamic 
>>> array, and then the runtime will assume that there are no 
>>> other dynamic arrays referring to the same memory.
>>>
>>> [snip]
>>
>> Another technique that works for many cases is to use an 
>> Appender (std.array). Appender supports reserve and clear, the 
>> latter setting the length to zero without reallocating. A 
>> typical use case is an algorithm doing a series of appends, 
>> then setting the length to zero and starts appending again.
>>
>> --Jon
>
> Appender reports clear? Are you sure?
>
> Seems appender is no different than string, maybe worse? string 
> as assumeSafeAppend, reserve and clear(although clear 
> necessarily reallocates. They should have a function called 
> empty, which resets the length to zero but doesn't reallocate.

See the Appender.clear documentation 
(https://dlang.org/phobos/std_array.html#.Appender.clear), the 
key piece being:

     Clears the managed array. This allows the elements of the 
array to be reused for appending.

I've tried using both dynamic array and appender in this way, 
setting the length of the dynamic array to zero vs using 
Appender.clear, in this cycle of fill-the-array by appending, 
operate on the array, clearing, and repeating. Appender is 
dramatically faster. And, if you look at GC reports you find that 
setting a dynamic array to zero creates garbage to collect, while 
Appender.clear does not. (Use the --DRT-gcopt=profile:1 command 
line option to see GC reports, described here: 
https://dlang.org/spec/garbage.html#gc_config).



More information about the Digitalmars-d-learn mailing list