Problems with GC, trees and array concatenation

Kirk McDonald kirklin.mcdonald at gmail.com
Fri Jun 1 09:54:57 PDT 2007


Babele Dunnit wrote:
> int main(char[][] args)
> {
> 
>     Population testPop1 = new Population;
>     Population testPop2 = new Population;
> 
>     Individual[40000] indi;
> 
>     for(int i = 0; i < 1000000; i++)
>     {
>         writefln("Round %d", i);
> 
>         testPop1.grow();
>         testPop2.grow();
> 
>         version (loseMemory){
>             indi[] = testPop1.individuals ~ testPop2.individuals;
>         }
> 
>         version (everythingOk){
>             indi[0..20000] = testPop1.individuals;
>             indi[20000..40000] = testPop2.individuals;
>         }
>     }
> 
>     return 0;
> }

It is worth reviewing what this line of code does:
     indi[] = testPop1.individuals ~ testPop2.individuals;
When you concatenate two static arrays, the result is a dynamic array. 
In other words, that concatenation allocates a new dynamic array of 
40,000 elements on the heap, copies the elements of the two sub-arrays 
into it. This array is then copied /again/ into the static array 'indi'.

The 'Ok' version avoids both the allocation (which is causing the GC to 
eat all that memory) and the double-copying.

-- 
Kirk McDonald
http://kirkmcdonald.blogspot.com
Pyd: Connecting D and Python
http://pyd.dsource.org



More information about the Digitalmars-d mailing list