Clearing an Array or Vector
There are many ways to clear an Array or Vector. I’m tired of seeing the foolish ones. Read this and make sure you’re not doing anything foolish:
Here’s one way to clear an Array or Vector that’s both wordy and slow:
vec.splice(0, vec.length);
Not only do you have to take the length of the vector and then go into a general-purpose slicing routine hoping that it optimizes the slice for you, but you had to type a lot. Here’s an even dumber way:
vec = vec.filter( function(cur:Point, index:int, vec:Vector.<Point>): Boolean { return false; } );
Yes, it uses functional programming. It’s horribly slow though. It’ll result in n calls to your AS3 function for a n-length vector. It’s also a ton to type. Unless your functional-style programming has made it really convenient for you to use that approach and really tough to use any other, don’t do it! Here’s a much more sane way that actually has a couple advantages:
vec = new Vector.<Point>();
The advantages here are that this won’t crash if vec is null and you get an entirely new vector. As such, it’s a good initializer, but not much else. It’s still more typing than the best way to do it. Here it is:
vec.length = 0;
Tada! This is the one with the least typing, the fastest speed, and the only one not doing another allocation and unreferencing an object. The downsides are that it will crash if vec is null and it won’t get you a new object if you need one. So there you have it. That is the clear winner as far as clearing a vector or array goes. This will also work in JavaScript, just not on Vectors of course.
#1 by Simon C on October 25th, 2010 ·
Although a Vector can use Array-like methods and member access such as vec[i] this article made me discover that unlike Arrays, a whole Vector cannot be cleared using vec = []
#2 by jackson on October 25th, 2010 ·
Yep, like in AS2 and JavaScript, the
[]
syntax alone evaluates to a newArray
object. Since you (unfortuantely) can’t assign anArray
to aVector
, you should get a compiler error.The more you read about
Array
andVector
, the more strange they get. Try doing a search for Array or Vector on this site for tons more information. Happy reading!#3 by Frank on July 27th, 2011 ·
This is all well and good, but what about when you want to clear a fixed length Vector such as one created like this:
myVector = new Vector.(3, true);
It’s going to throw an error if you try to set myVector.length = 0;
#4 by jackson on July 27th, 2011 ·
That would be a different meaning for “clear”. In the article, I used the term to mean “make the
Array
/Vector
have zero length”. But since a non-zero length fixed-lengthVector
can’t have its length changed to zero, you would want to “clear” it by changing its values back to a default. For that, the best you can do is afor
loop:#5 by skyboy on July 27th, 2011 ·
There’s also this: