Reputation: 3851
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;
}
}
}
Upvotes: 2
Views: 573
Reputation: 22604
Using the new
keyword will instantiate a new instance of PropertyRow. The GC won't free up memory after setting the variable to null
, 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):
var vec_size:int = 1000;
var myArray:Array = new Array (vec_size);
for (var i : int = 0; i< vec_size; i++) {
myArray[i] = new PropertyRow(); // if you're not setting any properties, you won't even need a temp variable ;)
}
If you are worried about garbage collection and reusing objects, also check out Adobe's reference on object pooling.
Upvotes: 4
Reputation: 370
You don`t need to create field for this temp object.
package com {
public class CreateList extends MovieClip {
//this is the array I will use to reference the objects
private var _theRows:Array = new Array();
public function CreateList() {
var newProperty:PropertyRow;
for (var i:uint = 0; i < 1000; i++ ) {
//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);
}
}
}
}
in this case newProperty will be a local variable that will destroyed automatically then function ends. You don`t need to null it anywhere.
Upvotes: 1