About tutorial 3 memory optimizing

Use this forum for questions on how to use .NET Memory Profiler and how to analyse memory usage.
Post Reply
Posts: 1
Joined: Wed Feb 14, 2007 11:26 pm

About tutorial 3 memory optimizing

Post by rbautista » Wed Feb 14, 2007 11:34 pm

In the tutorial 3 i find this sentence
"To optimize memory usage, instances should be as short-lived as possible. In this case, we can make the newly created Cell instances much more short-living by not storing a reference to them in the cells array. Instead we can simply use the newly created instance to update the instance already in the array.

The cell class provides a method named updatecell, chich updates a Cell using another one."

However i don´t understand which is the difference betwen update a existing cell versus store the new cell in the array. When the new Cell is stored in the array the old cell is not referenced anymore and may be Garbage collected.

However is a fact that updating the cell seems to use best the memory. But i don´t understand the reason.

Thanks in advanced and excuse my bad english.

Andreas Suurkuusk
Posts: 1029
Joined: Wed Mar 02, 2005 7:53 pm

Post by Andreas Suurkuusk » Thu Feb 15, 2007 11:58 pm

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.
Best regards,

Andreas Suurkuusk
SciTech Software AB

Post Reply

Who is online

Users browsing this forum: No registered users and 20 guests