A couple of questions about arrays and slices

Ali Çehreli acehreli at yahoo.com
Sat Jun 24 07:07:31 UTC 2023


On 6/20/23 19:09, Cecil Ward wrote:

 > 2.) I have a dynamic array and I wish to preinitialise its alloc cell to
 > be a certain large size so that I don’t need to reallocate often

To be complete, 'assumeSafeAppend' must be mentioned here as well. 
Without it, there will be cases where the GC cannot guarantee that there 
are no slices to this particular one; so it has to reallocate:

import std;

void main() {
     // An array with room for 100 elements
     int[] arr;
     arr.reserve(100);

     // Take note of current address of the elements
     auto ptr = arr.ptr;

     foreach (i; 0 .. 80) {
         // Add elements
         arr ~= i;

         // Was there a reallocation?
         if (arr.ptr != ptr) {
             writeln("relocated to ", arr.ptr, " at ", i);
             ptr = arr.ptr;
         }

         // Let's say our algorithm shrinks the array
         if (i == 50) {
             arr.length = 0;
             // assumeSafeAppend(arr);
         }
     }
}

Although the array has room for 100 elements, the program will print 
something similar to the following:

relocated to 7F058B02B000 at 51
relocated to 7F058B02C000 at 54
relocated to 7F058B02D000 at 58
relocated to 7F058B02E000 at 62
relocated to 7F058B02F000 at 66
relocated to 7F058B030000 at 74

When it's known that there is no other slice to the old elements, the 
programmer calls assumeSafeAppend() by uncommenting that line :o). Now 
there are no relocations. Sweet!

Ali



More information about the Digitalmars-d-learn mailing list