Skip to main content
Participating Frequently
June 23, 2011
Answered

Question about setting an array null vs setting each item null in the array and saving memory.

  • June 23, 2011
  • 1 reply
  • 443 views

Hello,

I'm trying to avoid any sort of memory leaks or garbage collection problems.

public class test{

var anArray:Array;

.

.

.

public function addObjects(){

  anArray = new Array();

  anArray[0] = new Something();

  anArray[1] = new Something();

  anArray[2] = new Something();

  for(var i:int = 0; i < anArray.length){
 
   anArray.addEventListener(MouseEvent.CLICK, doSomething);
   addChild(anArray);
 
  }

}

private function doSomething(event:MouseEvent){

  for(var i:int = 0; i < anArray.length; i++){

      anArray.removeEventListener(MouseEvent.CLICK, doSomething);

      removeChild(anArray);


  }


  anArray = null;


}


}

Is this efficient or do I have to include "anArray = null" after "removeChild(anArray)" in the for loop of my doSomething(event:MouseEvent) function?


Sorry if my question is confusing and thank you in advance.

This topic has been closed for replies.
Correct answer kglad

if there's no other reference to the new Something() instances, other than the array elements, nulling (or assigning a=[]) should work.

1 reply

kglad
Community Expert
kgladCommunity ExpertCorrect answer
Community Expert
June 23, 2011

if there's no other reference to the new Something() instances, other than the array elements, nulling (or assigning a=[]) should work.

KirtapAuthor
Participating Frequently
June 23, 2011

I see.  Thank you.  I've just been trying to be as careful as possible with memory and get confused once in a while with things.  Thanks again.

kglad
Community Expert
Community Expert
June 23, 2011

you can use System.totalMemory to test memory use and gc.

for example, the following shows you don't even need to remove event listeners for gc to take place (at least, in my test).  (i would not recommend that, though, because as flash player versions change, that may change.)

import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.events.Event;
import flash.display.MovieClip;

var a:Array;

var n:int=50000;
var m:int=10;

var t:Timer=new Timer(1000,m);
t.addEventListener(TimerEvent.TIMER,f);
t.start();

function f(e:Event):void {
    a = [];
    for (var i:int=0; i<n; i++) {
        a.push(new MovieClip());
        a[a.length-1].addEventListener("ce",ff);
    }
   
    trace(Math.round(System.totalMemory/1024));
}
function ff(e:Event):void{
   
}