Is this the correct, most efficient way to recycle objects when creating an array of objects?
package com {
public class CreateList extends MovieClip {
//this is the object I will be recycling
private var newProperty:PropertyRow;
//this is the array I will use to reference the objects
private var _theRows:Array = new Array();
public function CreateList() {
for (var i:uint = 0; i < 1000; i++ ) {
//null the object
newProperty = null;
//create a new instance of the object
newProperty = new PropertyRow();
//store a reference to the object before nulling it in the next for loop cycle.
_theRows.push(newProperty);
}
//null the last object that was created in the for loop
newProperty = null;
}
}
}
Using the
newkeyword will instantiate a new instance of PropertyRow. The GC won’t free up memory after setting the variable tonull, because the instances are still retained in the array. Therefore, using a member variable will not bring any performance advantage over using a temp variable within your creation loop.If you’re going to optimize your code for performance, you should first try to always use Vectors instead of Arrays.
IMPORTANT EDIT
As I’ve found out while testing vector performance for another question, this is true only for number types! If you are going to use a vector of any object type, Array will in fact be faster! The rest of my answer below still applies, though – just use Arrays instead of
Vector.<PropertyRow>.END EDIT
Then, if it’s avoidable, don’t use push(), but bracket syntax (only if you know the exact size of the vector – this is important, otherwise the bracket syntax won’t work):
If you are worried about garbage collection and reusing objects, also check out Adobe’s reference on object pooling.