Will emptying an Array = [ ] cause memory leak?

别说谁变了你拦得住时间么 提交于 2019-12-11 08:29:22

问题


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:


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.



来源:https://stackoverflow.com/questions/28491445/will-emptying-an-array-cause-memory-leak

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!