dynamic array .length vs .reserve - what's the difference?

Ali Çehreli acehreli at yahoo.com
Fri Jul 31 04:28:57 UTC 2020


On 7/30/20 4:42 PM, wjoe wrote:

 > So .capacity can't be assigned a value like length to reserve the RAM ?

Yes, a read-only property...

 >> auto a = b;
 >> b = b[0 .. $-1];
 >> b ~= someT;
 >>
 >> If that last line is done in-place, then it overwrites a[$-1].
 >
 > So this is a case of sharing being terminated ?

Yes but the "sharing being terminated" phrase was my attempt at 
explaining things, which did not catch on. :)

 > Expired structs are put back into (appended to) the array for reuse.
 > When the length of the array == 0, upon releasing a struct, this array
 > is reallocated which isn't supposed to happen. It should just grow like
 > it did with length > 1.
 > assumeSafeAppend should accomplish that :)

Yes, assumeSafeAppend is exactly for cases like that and it helps.

Another option, which is curiously said to be more performant in memory 
allocation than native arrays, is std.array.Appender. I've used 
function-local static Appenders to cut down on memory allocation. Here 
is an uncompiled pseudo code:

void foo() {
   static Appender!int a;
   a.clear();  // <- Clear state from last execution of this function.
               //    'a' still holds on to its memory.

   while (someCondition()) {
     a ~= 42;
   }

   // Use 'a' here
}

So, 'a' will have the longest length ever used up to this point, which 
may be exactly what is desired.

The cool thing is, because data is thread-local by-default in D, every 
thread gets their own copy of 'a', so there is not danger of data race. 
:) (Warning: Don't call foo() recursively though. ;) )

Ali



More information about the Digitalmars-d-learn mailing list