I recently read GC (Garbage Collector) related things and found several good articles. Although I was older (06 years old), it is worth reading, the GC (Garbage Collector) Here is mainly about flashplayer9. Even if the English language is poor, a very small number of statements are not translated, because I don't know how much it takes for everyone to wait. Welcome to the layout. ^_^ most of this article is from:
Http://www.gsk inner.com/blog/archives/2006/06/as3_resource_ma.html; where Part1 translated from: http://bbs.a iria.cn/actionscript/thread-3656-1-1.aspx. I have translated about five articles for others. We recommend that you read the "prelude" first, which will be of great help to understand this article.
Prelude:
Understanding the delete keyword
In one of my blog posts, how the garbage collector works in Flash Player 9, ceerick Nemi (formerly: Cédric né hémie, named Google's workshop) john raised a very good question: Why does an exception occur when deleting a non-dynamic class attribute? Does the delete keyword really delete the object from the memory? There are not many documents about this topic, and it is very difficult to find them. Most of the answers are speculation or speculation based on relevant tests. But my explanation must be completely correct (TRANSLATOR: suddenly think of a sentence in the crazy racing car: not burning or not professional ). If not, please tell me that I don't want to mislead anyone (=. = !) In my understanding, the D elete keyword deletes not only the value of the variable, but also the definition of the actual variable. This will undoubtedly release all its references and hand it over to the GC (Garbage Collector) for release. That is to say, delete does not directly Delete the objects pointed to by the reference from the memory.
In As2, the effect of this behavior is not obvious because the player does not support non-dynamic Class running. This means that deleting a variable is equivalent to setting the variable value as undefined. Because of this, the compiler will never throw a delete-related exception. They are just a little different. For example, if you try to delete the processing functions of the onpress and onmouseover events of a movieclip instance in As2, no matter which operation you delete will return an "undefined ", if you set it to undefined (no delete operation is required), you will find that the cursor of the corresponding operation still appears for the object directly set to undefined, and the delete operation will not appear. I am often convinced that this is the case. When determining whether a standard is required, the player will check whether the definition of the onpress event handler function exists, rather than based on its value ).
On the other hand, as3 supports non-dynamic classes. All classes are encapsulated in advance unless they declare dynamic classes with explicitly. At runtime, you cannot modify a encapsulated class or a member of its instance. Because of this, and according to ecmascript, delete only deletes dynamic attributes of dynamic classes and does not delete non-dynamic variables (or methods.
In ActionScript 2.0, you can use Delete to delete the attributes of an object or an object. In ActionScript 3.0, the delete operator follows ecmascript, which means that delete can only be used to delete the dynamic attributes of an object.
If you try to delete the non-dynamic attribute of an object, it will trigger an error message of the compiler:
1189> delete removes dynamically defined properties from an object.
Declared properties of a class can not be deleted. This error appears
Only when the compiler is running in strict mode.
In as3, delete returns a Boolean value to indicate whether the deletion is successful. You can try the following code:
VaR T: * = new timer (15); // No typing to get around the Compiler
Error
Trace (delete (T. Delay); // traces false, object is sealed so can't
Delete
Trace (T. Delay); // 15-delete never occurred
VaR O: * = {fun: "stuff "};
Trace (delete (O. Fun); // traces true, object is dynamic so can delete
Trace (O. Fun); // undefined-delete occurred
Question
Part1
At present, I am currently studying actionscript3.0. I am very excited by its capabilities. Its native execution speed brings many possibilities (the raw execution speed by itself provides so manypossibilities. Raw is not processed in the original sense, which means that after avm2 is introduced,
Actionscript3.0 greatly improves the execution speed, so it is possible to support more complex components ). It introduces E4X, sockets, byte array objects, new display list models, regular expressions, normalized events and error models, and other features. It is a dazzling Large Complex
Stew. The greater the ability, the greater the responsibility (TRANSLATOR: from Spider-Man), which is true for actionscript3.0. Introducing these new controls has a side effect: the Garbage Collector no longer supports assumptions such as automatic garbage collection. That is to say, after the Flash Developer transfers to actionscript3.0, he must have a deeper understanding of how garbage collection works and how to program it to make it work more effective. Without this knowledge, even if you create a seemingly simple game or application, the SWF File Memory may leak, consume all system resources (CPU/memory), leading to system suspension or even machine restart. To understand how to optimize your actionscript3.0 code, you must first understand how the garbage collector works in flashplayer 9. Flash has two ways to find and remove non-active objects. This article explains the two technologies and describes how they affect your code. At the end of this article, you will find a garbage collector simulation program running in flashplayer9, which vividly demonstrates the concepts explained here. The garbage collector is a background process that recycles the memory occupied by objects that are no longer used in the program. An Inactive object is no longer referenced by any other active object. To facilitate understanding of this concept, it is very important to realize that, except for non-native types (Boolean, String, number, uint, INT), you always access the object through a handle, instead of the object itself. When you delete a variable, you actually delete a reference, not the object itself. The following code can easily describe this
One point: ActionScript code
// Create a new object, and put a reference to it in:
VaR A: object = {FOO: "bar "}
// Copy the reference to the object into B:
VaR B: Object =;
// Delete the reference to the object in:
Delete ();
// Check to see that the object is still referenced by B:
Trace (B. Foo); // traces "bar", so the object still exists.
If I change the sample code above and delete B, it will make the object I created no longer have active references and wait for the garbage collector to be recycled. Actionscript3.0 the Garbage Collector uses two methods to locate non-referenced objects: reference counting method and Mark clearing method.
Reference counting method reference counting method is a simple method for tracking activity objects, which is used from actionscript1.0. When you create a reference pointing to an object, add 1 to the Reference Counter of the object; when you delete a reference of the object, the counter minus 1. When the counter of an object becomes
0, the object will be marked for the garbage collector to recycle. This is an example: The ActionScript code
VaR A: object = {FOO: "bar "}
// The object now has a reference count of 1 ()
VaR B: Object =;
// Now it has a reference count of 2 (A & B)
Delete ();
// Back to 1 (B)
Delete (B );
// Down to 0, the object can now be deallocated by the GC
The reference counting method is simple, and it does not impose a huge burden on the CPU; in most cases, it works normally. Unfortunately, the garbage collector using the reference counting method has a low validity rate when it encounters a loop reference. Circular Reference refers to cross-Object Reference (directly or indirectly implemented through other objects. Even if the application no longer references this object, its reference counter is still greater than 0, so the Garbage Collector will never be able to collect them.
The following code demonstrates how loop reference works:
VaR A: object = {}
// Create a second object, and reference the first object:
VaR B: Object = {FOO: };
// Make the first object reference the second as well:
A. Foo = B;
// Delete both active application references:
Delete ();
Delete (B );
In the above Code, all active references in the application are deleted. I have no way to access these two objects in the program, but the reference counters of these two objects are both 1 because they reference each other. Circular references can also be more responsible (A references C, C references B, B references a, and so on) and are difficult to process with code. XML objects in Flash Player 6 and 7 have many circular references: Each XML node is referenced by its child and father, so they are never recycled. Fortunately, Flash Player 8 has added a new garbage collection technology called Mark-clearing.
Mark-clear method actionscript3.0 (and flashplayer 8) the Garbage Collector uses 2nd kinds of policy mark-clear method to find inactive objects. Flashplayer starts from the root object of your application (simply called root in actionscript3.0) until every reference in the program marks the referenced object. Next, flashplayer traverses all marked objects. It recursion the entire object tree according to this feature. And mark everything that can be reached from an activity object. After this process is completed, flashplayer can safely assume that all unmarked objects in the memory no longer have any active references, so they can be safely deleted. Figure 1 demonstrates how it works: the green reference (arrow) is marked by Flash Player, the green object is marked, and the white object is recycled.
Figure 1. flashplayer uses the mark clearing method to mark objects that no longer have active references-the clear method is very accurate. However, because Flash Player traverses your entire object structure, this process consumes too much CPU. Flashplayer 9: Adjust the iteration ID to clear the CPU usage. This process is no longer completed once in several stages, but occasionally runs. The deferred (executed) garbage collector and the uncertain flashplayer 9 Garbage Collector Operations are deferred. This is a very important concept to understand: When all references of your object are deleted, it will not be deleted immediately. Instead, they will be deleted at an uncertain moment in the future (from the developer's perspective ). The garbage collector uses a series of heuristic techniques such as viewing the size of Ram allocation and memory stack space, and other methods to determine when to run. As a developer, you must accept the fact that it is impossible to know when an inactive object will be recycled. You must also know that the inactive objects will continue to exist until the Garbage Collector recycles them. So your code will continue to run (the enterframe event will continue), the sound will continue to play, the loading will also happen, and other events will also touch
And so on. Remember, in Flash Player, You do not have permission to control when the garbage collector is running to recycle objects. As a developer, you need to clear useless object applications in your game or application as much as possible.
Two examples:
Http://www.adobe.com/devnet/flashplayer/articles/garbage_collection.html #
Http://www.adobe.com/devnet/flashplayer/articles/garbage_collection.html #
Part 2
As3 provides developers with a faster code running speed and more functions and more powerful APIs. However, unfortunately, with the enhancement of functions, developers have higher and higher requirements for professional capabilities. This article will focus on the features of as3 in resource management and some headaches that may arise from these features. In the next article, I will introduce some countermeasures that can be used by us. The newly introduced display list model has the greatest impact on resource management in as3. In flash 8 and earlier versions, when a display object is removed (using removemovie or unloadmovie ), the object and all its subnodes will be immediately deleted from the memory and all code running the object will be terminated. Flash Player 9 introduces a more flexible display list model, and regards display objects (sprites, movieclips, etc) as a general object. This means that developers can do a lot of interesting things, such as customizing the Display object container (moving a display object from one display list to another ), read the instantiated Display object from the generated SWF file. Unfortunately, these display objects will be processed by the garbage collector as common objects. This will lead to some potential problems.
Question 1: Dynamic Content
One of the obvious problems occurs in the dynamic instances of Sprite-related or other containers. When you want to remove this object after a certain period of time, Sprites (or other containers) there will be an obvious problem: when you remove it from the stage, the display object is no longer on the display list, but in fact it is still not cleared in the memory. If you do not clear all references or listeners for this clip, it may be far from being deleted from the memory. It is often worth noting that the Display object not only occupies memory, but also is still executing its internal code, such as timer, enterframes and its related external listeners. Currently, a Sprite applied to the game is executing an internal enterframe event. Each frame executes some operations and judges other game elements near it. In as3, even if you delete it from the display list (removechild) and set all its references to null
Before the garbage collector is recycled, it continues to execute code in enterframe. Before deleting a Sprite, you must make it clear that the "enterframe listener has been deleted ". Suppose there is a video clip that listens to the mouse movement event from the stage. Before you remove its listener, even if the clip has been deleted (Deleted), every time you move the mouse, the code will be executed, that is, the clip will be run forever and used as a reference for dispatching events from the stage. Suppose: In some Sprite instances that are correlated with each other and are in different States (for example, some Sprite instances that are in instantiation and some are deleted ), or when you fail to clear all references of an object before deleting it. You may not find that this detail causes your CPU usage to rise straight, reducing the execution speed of your programs or games, or making your computer unresponsive. There is no way to force the Flash Player to immediately delete a display object and stop its code execution. You must delete it from a container
Manually process a display object. In the next article, I will introduce countermeasures. Here is an example (Flash 9 player is required). Click the create button to create a new sprite instance. The sprite contains a counter and is displayed. Click the Remove button and observe how the counter changes. In fact, the reference of Sprite has been set to null. You can create several more instances to observe how this problem deteriorates a program. The code will be at the bottom of this article.
Http://www.gsk inner.com/blog/archives/2006/07/as3_resource_ma_1.html
Question 2: The loaded content assumes that the loaded SW
F files are also treated as common objects. It is easy to think of problems you may encounter. Like display objects, there is no clear and effective way to delete the SWF loaded content from the memory or immediately stop running it. If it is left blank, the loader called will reference all the loaded SWF, and it will eventually be collected by the GC (Garbage Collector.
Consider two such scenarios:
1. You have created a shell for flash experiments. This experiment is cutting-edge, and it will make the CPU usage reach the highest. A user clicks the button to load an experiment. after observing the experiment, the user clicks the button to load the second experiment. Even if the first reference is cleared, it is still running in the background. While the second experiment is running, the load of the two experiments has exceeded the maximum computing power of the CPU.
2. A customer asks you to create a program to read SWF files from other developers. The developers added listeners to the stage, or used other methods to create some references pointing to the SWF. You cannot delete its contents until the application is closed, and it will remain in memory and occupy the CPU. Even if they do not have an "internal reference", they will continue to be executed, knowing that the next GC (Garbage Collector) will release them. For project security considerations, when loading third-party content, you must understand that you cannot control the deletion or execution of the content. When a SwF is loaded, it is easy to keep running with your program. Even if it is deleted, the SWF loaded when interaction occurs may continue to capture or interfere with users. Another example is the same as the first one, except that dynamic instances are not used each time a SwF is loaded.
Two scenarios mentioned above are listed on the following page:
Http://www.gsk inner.com/blog/archives/2006/07/as3_resource_ma_1.html
Question 3: timeline
We hope this problem can be solved in the final version. This article was published in 2006. In as3, the timeline can be operated by code. When playing a video, it dynamically instances or deletes the Display object. This means that you will encounter the same problem as problem 1. Although a clip is deleted from the stage, it is still stored in the memory. Before being recycled, it continues to execute all its internal code. This is not what programmers expect, and of course it is not what flash designers expect.
Here is an example of the same principle, but this time it is deleted and instantiated between two frames.
Http://www.gskinner.com/blog/archives/2006/07/as3_resource_ma_1.html
What is Adobe thinking? Or, why? When the Java developer sees this problem, he may say, "What then ?". This difference is reasonable.
Solution: Flash developers are not used to Manual Interference in memory management (because they did not have this problem before ), java and C ++ developers are used to powerful GC (both automatic and manual ). These problems are inherent defects of the latest memory management language. Unfortunately, these problems cannot be avoided. On the other hand, flash brings about many rare issues in other languages (including some of flex ). In Flash content, a lot of idle or passive code is often executed, especially when Java and flex are interacting (generally speaking, many intensive operations are closely linked with entry-level input ). Flash projects often read external third-party content (the code quality is usually poor ). Flash developers have fewer tools, materials, and frameworks available. As far as I know, the background of Flash developers generally comes from: music, art, commerce, philosophy, or anything else, except professional programmers. This diversity brings amazing creativity and content, but they are not prepared to discuss the issue of resource management.
Summary
Resource management will become an important part of as3. Ignoring this problem may lead to slow program running or totally dragging the user's system down. So far, there is no clear way to delete the Display object from the memory and stop its internal code running. This means that we have the responsibility to properly process the created object. We hope that through communication, we can find an optimal method and framework to solve this problem more easily.
Code involved in this article:
Http://www.gskinner.com/blog/assets/resMgt2/resourceManagement2.zip
Part 3
In Part 3, we will focus on some new tools (as3/flex2) to make memory management more effective. In terms of memory management, there are only two official functions directly related to memory management, but they are usually useful. Below are some unofficial supplements. Of course this is not the only method.
System. totalmemory is a simple tool, but it is very important because it is the first tool that developers can use in real time in flash. It allows you to monitor the memory usage of the Flash Player in real time. More importantly, you can use this to determine whether to throw an exception to terminate the negative experience that will be brought to users.
The following is an example:
Import flash. system. system;
Import flash.net. navigatetoURL;
Import flash.net. URLRequest;
...
// Check our memory every 1 second:
VaR checkmemoryintervalid: uint =
Setinterval (checkmemoryusage, 1000 );
...
VaR showwarning: Boolean = true;
VaR warningmemory: uint = 1000*1000*500;
VaR abortmemory: uint = 1000*1000*625;
...
Function checkmemoryusage (){
If (system. totalmemory> warningmemory & showwarning)
{
// Show an error to the user warning them that we're re
Running out of memory and might quit
// Try to free up memory if possible
Showwarning = false; // so we don't show an error
Every second
} Else if (system. totalmemory> abortmemory ){
// Save current user data to an LSO for recovery
Later?
Abort ();
}
} F
Unction abort (){
// Send the user to a page explaining what happpened:
NavigatetoURL (New URLRequest ("memoryerror.html "));
}
This line can be implemented in many ways, but at least it proves that this line is a good purpose. It is worth noting that totalmemory is a global variable (shared value) used by a single process. A process may have only one window, or multiple browser windows, depending on the browser, operating system or number of windows opened.
Weak reference
Among the many new features of as3, I am very happy to see "weak references ". This reference will not be used by the garbage collector as a basis for determining whether the object is recycled. Its function is: if an object has only weak references left, the object will be reclaimed by the garbage collector in the next round. However, weak references only support two types: the first is the event listener that is often troublesome due to the memory management mechanism. I strongly recommend that: Whenever a listener is added, the fifth parameter option, that is, the weak reference is set to true.
The following is an example of parameter settings:
Someobj. addeventlistener ("eventname", listenerfunction, use
Capture, priority, weakreference );
Stage. addeventlistener (event. Click, handleclick, false, 0, tr
UE );
// The reference back to handleclick (and this object)
Will be weak.
For more information about weak references see: http://www.gskinner.com/blog/archives/2006/07/as3 _
Weakly_refe.html
Another weak reference supports dictionary object. Generally, the first one is set during initialization.
The parameter is true. The following is an example:
VaR dict: dictionary = New Dictionary (true );
Dict [myobj] = myotherobj;
// The reference to myobj is weak, the reference
Mytherobj is strong
For more information about the introduction and application of dictionaries in ActionScript 3, click the feature to hook weak references to other content. For example, you can use weak references to create weakreference and weakproxyreference classes to create weak references for any object.
Weakreference class
Weakreference uses dictionary to store weak references to hook weak references to any other object. This class has some overhead in instantiation and access, so I suggest applying it to some objects that may not be released and are large. Although these codes cannot replace those that make the object "break down", they can help you ensure that large data objects are broken down by the garbage collector.
Import com. gskinner. utils. weakreference;
VaR datamodelreference: weakreference;
Function registermodel (data: bigdataobject): void {
Datamodelreference = new weakreference (data );
}.
..
Function dosomething (): void {
// Get a local, typed reference to the data:
VaR datamodel: bigdataobject = datamodelreference. Get ()
As bigdataobject;
// Call methods, or access properties of the data
Object:
Datamodel. dosomethingelse ();
}
From a good code structure, this is a good solution because it ensures good security for your data type and has no ambiguity (non-ambiguou ). These code is prepared by those who want to quickly implement this function. I also integrate it into another weakproxyreference class (same
Is also a good example of learning proxy.
Weakproxyreference class
Weakproxyreference uses the proxy class to proxy weak referenced objects. Its effect is basically the same as that of the weakreference class. weakproxyreference can directly call the method of the weak reference object and pass it directly to the target. Weakproxyreference is lost.
And has a little bit of ambiguity code. In other words, it may throw a runtime error. (Especially when you try to access a non-stored attribute in an object) but there is no compilation error.
Import com. gskinner. utils. weakproxyreference;
VaR datamodel: object; // note that it is untyped, and not
Named as a reference
Function registermodel (data: bigdataobject): void {
Datamodel = new weakproxyreference (data );
} F
Unction dosomething (): void {
// Don't need to get () the referent, you can access
Members directly on the reference:
Datamodel. dosomethingelse ();
Datamodel. Length ++;
Delete (datamodel. someproperty );
// If you do need access to the referent, you need
Use the weak_proxy_reference namespace:
VaR BDO: bigdataobject =
Datamodel. weak_proxy_reference: Get () as bigdataobject;
}
A method that forces garbage collection (not recommended)
In my previous article, I said that in as3, the garbage collection cycle is uncertain and there is no way to know when it will run next time. Strictly speaking, this sentence is not completely correct. There is a skill that forces the Flash Player to execute a garbage collection, this technique is convenient for you to explore garbage collection and test your program during the development period, but it must not appear in the developed product because it will damage the load capacity of the processor. At the same time, it is not officially recommended, so you cannot rely on its functions to improve the substantive functions.
To forcibly execute garbage collection (indicating counting or referencing clearing), you must execute the same localconnection twice. In this case, the system throws an exception, so you must prepare the exception capture for it (try/catch)
Try {
New localconnection (). Connect ('foo ');
New localconnection (). Connect ('foo ');
} Catch (E :*){}
// The GC will perform a full mark/sweep on the secondcall.
Repeat once again: This method can only be used for testing within the development cycle. It must not appear in a developed product!
To sum up, there is no doubt that: ActionScript 3 has brought more work to developers in resource management. Although we only have some of the response tools we just mentioned, there are always better countermeasures than none, and Adobe has at least noticed this problem. We believe that effective countermeasures and methods can be used with these tools reasonably.
You can well manage Flash 9 and flex 2 projects.
Download weakreference and weakproxyreference.
Http://www.gskinner.com/blog/assets/WeakReference.zip
Conclusion
Additional information:
Source: http://www.tan66.cn /? P = 11
In the air program, we found a way to quickly activate GC sweep. That is, the window is minimized, and environmental protection is instantly realized.
Of course, in order to be quiet, we need to restore the window. You can write these two sentences together. The precondition is that the current status is not minimized.
Stage. Window. Minimize ();
Stage. Window. Restore ();
The problem is that the window is reduced and changed back. Therefore, the main program window can be invisible during actual development.
Visible = false;
Put the content to be displayed in other windows. Of course, do not forget to add the code that controls the exit of the main program window.