Will emptying an Array = [ ] cause memory leak?

2019-09-01 05:58发布

Hey guys I was wondering if removing all objects on the stage like so:

//bomb
for each (var bomb:mcBomb in aBombArray)
{
    bomb.parent.removeChild(bomb);
    aBombArray = [];
    bomb = null;
}

at the end of the game cause a Memory Leak? Is this removing all objects in the array and setting it back to 0? Should I instead use aBombArray.length = 0;?

I have all my arrays removed like this at the end of the game. I notice that when you get the 'Game Over' screen the memory doesn't decrease it instead still climbs. Not sure if this might be the problem.

Thanks guys.

1条回答
对你真心纯属浪费
2楼-- · 2019-09-01 06:39

There's a few problems with your code, but I think what you are asking is whether setting an Array property to [] will be enough to dereference all the elements that used to be in that array. The answer is yes, as long as there were no other references to that array or elements in the array. For example:

var bombs:Array = [a, b, c];
var bombs2:Array = bombs;
bombs = [];
// a, b, c remain in memory because they are still referenced by bombs2

A slightly more thorough way to clear the array is to set its length to 0. In that case all references to the array will be cleared, because you didn't re-assign the property, you modified the array directly:

var bombs:Array = [a, b, c];
var bombs2:Array = bombs;
bombs.length = 0;
// both bombs and bombs2 are cleared, so a, b, c will be removed from memory

Of course, any references to the elements within the array, including in other arrays, will keep those objects in memory.

var bombs:Array = [a, b, c];
var bombs2:Array = [a, b];
bombs.length = 0;
// bombs2 still references a, b so they will remain in memory

Going back to your original code, the following should work, assuming there are no other references to the elements in the array as in the previous examples:

for each (var bomb:mcBomb in aBombArray) {
    bomb.parent.removeChild(bomb);
}
aBombArray.length = 0;

Note that:

  1. The array is not cleared until the loop finishes.
  2. There's no need to set bomb = null in each iteration, because each iteration will immediately assign a new value, and as a local variable it will be de-referenced when the function scope returns anyway.

Finally, you mention that you don't see the memory go down at the end. Garbage collection happens at some unknown time in the future when the runtime decides is a good time, so you don't see memory released as soon as the objects are completely de-referenced. In debugging environments you can use System.gc() to test if memory is freed.

I recommend that you use Adobe Scout or a profiler to see what objects are actually sticking around in memory.

查看更多
登录 后发表回答