As3 - How to clear an array efficiently?
Asked Answered
B

5

20

I've been looking to clear an array in ActionScript 3.

Some method suggest : array = []; (Memory leak?)

Other would say : array.splice(0);

If you have any other, please share. Which one is the more efficient?

Thank you.

Brynne answered 10/2, 2010 at 14:55 Comment(1)
Memory leak ? Garbage collection!Iaea
P
29

array.length = 0 or array.splice() seems to work best for overall performance.

array.splice(0); will perform faster than array.splice(array.length - 1, 1);

Paramecium answered 10/2, 2010 at 15:4 Comment(3)
I know this is an old topic but how about setting an array to null?Orthogenic
Actually array = null; gets rid of the Array itself instead of just cleaning it. Its basically the same that happens when you array = [];, the previous array reference is lost and will probably be garbage collected (which might not be the wanted outcome).Talion
Why do not array = new Array()?Natika
I
6

For array with 100 elements (benchmarks in ms, the lower the less time needed):

// best performance (benchmark: 1157)
array.length = 0;
// lower performance (benchmark: 1554)
array = [];
// even lower performance (benchmark: 3592)
array.splice(0);
Iaea answered 27/2, 2013 at 11:16 Comment(0)
E
2

I wonder, why you want to clear the Array in that manner? clearing all references to that very array will make it available for garbage collection. array = [] will do so, if array is the only reference to the array. if it isn't then you maybe shouldn't be emtpying it (?)

also, please note that`Arrays accept Strings as keys. both splice and lenght operate solely on integer keys, so they will have no effect on String keys.

btw.: array.splice(array.length - 1, 1); is equivalent to array.pop();

Epizoic answered 10/2, 2010 at 16:35 Comment(4)
I do want to make it avaible to garbage collection, I want to empty it.Brynne
Pretty sure arrays in AS3 don't accept strings as keys. Objects do, but not Arrays.Tetchy
@Omnomlets: you're wrong. next time, try verifying your statements.Epizoic
You're right. I suppose that's because Array extends Object in the first place. Thanks! You learn something every day.Tetchy
B
2

There is a key difference between array.pop() and array.splice(array.length - 1, 1) which is that pop will return the value of the element. This is great for handy one liners when clearing out an array like:

while(myArray.length > 0){
     view.removeChild(myArray.pop());
}
Buggy answered 6/6, 2012 at 23:33 Comment(0)
O
1
array.splice(0,array.length);

this has always worked pretty well for me but I haven't had a chance to run it through the profiler yet

Oyler answered 3/5, 2012 at 14:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.