2011-12-18 38 views
2

这是在创建对象数组时回收对象的正确,最有效的方法吗?AS3 - 回收对象

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; 
     } 
    } 
} 

回答

4

使用new关键字将实例化PropertyRow的新实例。将变量设置为null后,GC不会释放内存,因为实例仍保留在阵列中。因此,使用成员变量不会在创建循环中使用临时变量带来任何性能优势。

如果您要优化代码的性能,您应该首先尝试始终使用矢量而不是阵列。

重要EDIT

正如我发现在测试向量表现为another question,这是真的只为数字类型!如果你打算使用任何对象类型的向量,Array实际上会更快!下面我的答案的其余部分仍然适用 - 只需使用数组而不是Vector.<PropertyRow>

编辑完

然后,如果它是可以避免的,不使用推(),但括号语法(只有当你知道向量的确切大小 - 这是很重要的,否则括号语法韩元“T工作):

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 ;) 
} 

如果你担心垃圾回收和再利用的对象,也object pooling检查了Adobe的参考。

1

您不需要为此临时对象创建字段。

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); 
      } 
     } 
    } 
} 

在这种情况下,newProperty将是一个局部变量,它将自动销毁,然后函数结束。你不需要在任何地方清零。