The delete keyword in Flash is used to remove variable definitions. It doesn't delete objects from memory (this happens behind the scenes using something called the "Garbage Collector"), it just takes a variable you've created and gets rid of it so that it is no longer accessible and is no longer present through iteration (for..in loops, etc.).
Internally, the Garbage Collector, or GC for short, knows when to physicially delete objects in memory when they no longer have any variables that reference them. So, for example, if you have two variables A and B and they both reference ObjectX, deleting variable A will not cause ObjectX to be removed from memory by the GC because variable B still references it. However, if you delete both variables A and B, there will be no more references to ObjectX and the GC will recognize that it needs to be removed from memory
ActionScript Code:
var a:Object = new Object();
var b:Object = a; // reference same new Object();
delete a;
trace(b); // [object Object] - still exists in memory
delete b;
// GC will mark object for deletion from memory
This works practically the same way for Flash 8 and Flash 9 (ActionScript 1, 2, and 3), though some changes were made in 8 to improve the GC. (Note: GC deletion from memory is not immediate.)
Though the GC has not really changed much with ActionScript 3 and the new virtual machine that runs it, what has changed is the behavior of the delete keyword. Now, the delete keyword only works for dynamic properties of a class instance and not declared class memebers (variables or methods). With ActionScript 1 and 2, delete could be used for anything. ActionScript 3 only lets you delete dynamic variables and locks those which are not.
ActionScript Code:
// ActionScript 2
class DeleteVarClass {
public var myVar:Number;
function DeleteVarClass() {
myVar = 1;
trace(myVar); // 1
delete myVar;
trace(myVar); // undefined
}
}
ActionScript Code:
// ActionScript 3
package {
public class DeleteVarClass {
public var myVar:Number;
public function DeleteVarClass() {
myVar = 1;
trace(myVar); // 1
delete myVar;
trace(myVar); // 1
}
}
}
Because myVar in the above example was declared as part of the class definition, it cannot be deleted using delete in ActionScript 3.
Since you cannot delete class members in ActionScript 3, if you want to cause a variable to no longer reference an object or value in memory you should set your variable's value to null instead of deleting it.
ActionScript Code:
myVar = null;
If all variable references to an object are null, the GC will mark it for deletion and it will eventually be cleared from memory.

0 评论:
发表评论