views:

51

answers:

1

the following method will be called many times. i'm concerned the continuous call for new rectangles will add potentially unnecessary memory consumption, or is the memory used to produce the previous rectangle released/overwritten to accommodate another rectangle since it is assigned to the same instance variable?

private function onDrag(evt:MouseEvent):void
        {
        this.startDrag(false, dragBounds());
        }

private function dragBounds():Rectangle
    {
    var stagebounds = new Rectangle(0 - swatchRect.x, 0 - swatchRect.y, stage.stageWidth - swatchRect.width, stage.stageHeight - swatchRect.height);
    return stagebounds;
    }
+3  A: 

Hi there,

It is a quick question, but very important! Too few ActionScript developers care enough the even consider these things. So kudos to you!

Everytime you create a new rectangle, new memory is being allocated for it. As soon as all references to that rectangle are removed it becomes eligible for garbage collection (GC), meaning the next time the GC runs it'll be freed from memory. (In this case all references are removed when you call stopDrag())

An instance of Rectangle takes very little memory up, and with the garbage collector running at regular intervals, instances will constantly be cleaned up. Additionally, we can be certain that no more than one will be created at any given time without a previous instance being made available for GC. (Assuming you'll be calling stopDrag before you call dragBounds again.)

Really, this is a case where you just don't need to worry about it. Your code is fine as is. You would need many thousands of Rectangles (like millions, at one time) before you run into any potential issues.

Tyler Egeto
thanks for the response, tyler. so i now understand that stopDrag() will remove the references from startDrag(). but what if dragBounds() was called many many times but wasn't called by startDrag()? assume the rectangle is a large, memory hogging object. would i make it's instance variable accessible to the whole class in order to nullify it before creating a new one like this? -- if (stageBounds) {stageBounds = null}; stageBounds = new Rectangle(...); --
TheDarkInI1978
Nulling a value doesn't free the it from memory, only removes the reference, potentially making it available for GC. As long as all references are cleaned up, the GC will find and remove it. You can't force this to occur. With large objects, you can reuse them rather then creating new ones. This is can be beneficial if the cost of creating a new one is greater than maintaining one you know you will need again soon.
Tyler Egeto