I wrote this simple program to test out my understanding of memory allocation :-

    import std.stdio;

    void main()
    {
        int [] array = new int[250];

        writeln(array.length, " elements ", array);

        // Append one value to the array
        array ~= 123;
        writeln(array.length, " elements ", array);
    }

I compiled it with 'dmd test.d -profile=gc'

After running it, the profile report was :-

    bytes allocated, allocations, type, function, file:line
               2000               1 int[] D main test.d:5
                  4               1 int[] D main test.d:10

This is not how I expected it to be. I would have expected that the runtime either did not have to allocate at all at line 10 to add a new element because there was already space or it would have to allocate space for the new enlarged array and copy the array to it, in which case I'd expect it to allocate 2004 bytes (or more) to copy the enlarged array in to.

I would not expect that it could have allocated 4 bytes to add an item separably from the original 2000. Is there some way that the runtime can grown the original allocation by 4 bytes and that's what I'm seeing? If so, is there a limit to how much it can do this?

Can anyone help me understand what is going on here?

Reply via email to