Page 1 of 1

Question on code in Lesson 3 of tutorial

Posted: Wed Mar 08, 2006 10:31 pm
by braham_5
Hello! My coworkers and I were struggling with this code excerpt from Lesson 3 of the tutorial. In the tutorial, we ended up making the following mod to the Board.NextGeneration() method in its loop:

Code: Select all

            for( int r=0; r < RowCount; r++ )
                for( int c=0; c < ColumnCount; c++ )
                    Cell newCell = cells[ c, r ].NextGeneration();
                    //old line
                    //cells[ c, r ] = newCell;
                    //new line
we removed the 'old line' and added the .UpdateCell call; this improved memory utlization (less average difference in total bytes vs. live bytes as the program ran). The tutorial said that this works because in the 'old line', a particular instance (the one in the array being replaced I assume) will not be GCed until another 15,000 instances are created (the loops are completed in essence).

Can someone explain this comment, or why it works like that? I thought arrays held pointers to objects, and when an element is replaced, the pointer is 're-pointed'. The old object would then be GCed (or mark for GC) right away in 'old line', instead of the newCell instance in 'new line'; same net effect in my mind. Or what is the GC doing?

Sorry, relatively inexperienced in this particular part of memory optimization...and hopefully I posed the question semi-clearly :)

Posted: Thu Mar 09, 2006 8:55 pm
by Andreas Suurkuusk
It is true that the old cell that is replaced in the original code will be eligible for GC directly after the assignement, e.g.

Code: Select all

// This assignment will overwrite the reference to the old cell at [c, r],
// making the old cell eligible for GC.
cells[ c, r ] = newCell;  
However, the newCell instance is now referenced by cell[c,r]. This reference will not be overwritten until the next time the board is updated. Before that, another 14,999 cells have been created, and 14,999 other "old" cells have become eligible for GC.

In the modified code, the newly created cell is only used to update the "old" cell, and then the newly created cell can be GCed.

The point that we try to make in the tutorial is that even though the number of allocations is the same, and the number of live instances is the same, the memory utilization will be much better in the modified code, since the newly created instances are much more short-lived.