这是创建对象数组时回收对象的正确、最有效的方法吗?
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;
}
}
}
最佳答案
使用new
关键字将实例化 PropertyRow 的新实例。将变量设置为 null
后,GC 不会释放内存,因为实例仍然保留在数组中。因此,与在创建循环中使用临时变量相比,使用成员变量不会带来任何性能优势。
如果您要优化代码的性能,您应该首先尝试始终使用向量而不是数组。
重要编辑
正如我在测试 another question 的矢量性能时发现的那样,这仅适用于数字类型!如果您要使用任何对象类型的向量,数组实际上会更快!不过,我下面的其余答案仍然适用 - 只需使用数组而不是 Vector.<PropertyRow>
.
结束编辑
然后,如果可以避免,不要使用push(),而是使用括号语法(只有当你知道向量的确切大小时 - 这很重要,否则括号语法将不起作用):
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 ;)
}
如果您担心垃圾收集和重用对象,还可以查看 Adobe 关于 object pooling 的引用资料。 .
关于flash - AS3 - 回收对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8551328/