[Transfer] as3 garbage collection

Source: Internet
Author: User
Tags root access
GC has nothing to do with Memory leakage

Garbage collection is a traditional topic that has been discussed by countless people.

Action Script uses a memory management mechanism similar to Java and does not recycle the memory of discarded objects in real time. Instead, it executes a GC (gabage collection) at a specific time) operation to release the memory of the discarded object, avoiding repeated performance problems that need to be recycled.

However, it is important to note that this only determines the time to recycle, not the content to be recycled. This delayed execution of memory recovery is also a superficial phenomenon. No matter when GC is executed, the memory that can be recycled in the end. The only impact is that because recovery is delayed, you cannot intuitively see the memory recycle process because an object is deprecated.

However, this is irrelevant to solving Memory leakage.

Memory leakage means that when you destroy an object, the memory occupied by it cannot be recycled. This will cause a smaller and smaller available memory and eventually overflow, in an environment with insufficient memory, the system will crash. There are various causes, but they are generally caused by developers' negligence and are not provided to the system as a basis for the destruction of objects.

Although GC execution has nothing to do with Memory leakage, If GC execution is not performed before the test, you will not see the actual amount of memory that cannot be recycled at that time, memory leakage refers to the increase in the amount of memory that cannot be recycled. Therefore, the GC method is indispensable for testing memory recovery. A test case that does not use the GC method makes no sense, because it is mixed with contingency (when to execute GC ). Many of the absurd test results are caused by the failure to execute GC in the correct position.

Although flash player does not have a manual GC in the open release status, the debugging version is usable and can be tested. In addition, the following hack code can also trigger GC in the release phase.

try {    new LocalConnection ().connect ( "gc" );    new LocalConnection ().connect ( "gc" );} catch ( e:Error ) {}

However, I once again stressed that calling GC is only for testing. In actual products, calling GC is basically meaningless (except for controlling GC timing). In short, if your program has a memory leak, it must have nothing to do with GC, do not waste any time or energy in such a place.

Automatic GC is triggered only when the memory is applied.

The GC of avm2 is triggered based on the current memory usage each time the memory is applied. Memory application is a necessary factor. Therefore, if you do not apply for memory, it will not perform GC even if the memory reaches a high value.

This is indeed unreasonable. However, in the actual environment, it is rare to never request memory. Even if it appears, it may not be in the high memory value. This situation mainly occurs in the test environment, causing some people to doubt whether the automatic GC function is normal. In fact, this is not necessary.

Garbage collection conditions in Flash

In avm2, except for the special bitmapdata, you must call dispose to reclaim the memory. Other parts use the reference counting method and the mark clearing method to determine whether the memory should be recycled, in addition, there is no API for active recovery. For details, please read this log and I will not repeat it.

Http://www.cnblogs.com/cos2004/archive/2010/11/07/1870980.html

Therefore, to recycle an object, you only need to ensure that no object references it, and its method is not used as an event function -- or that it has no connection with other parts of the program, it satisfies the reference counting standard and will be recycled. To do this, we generally say "execute removechild, removeeventlistener, and set its reference to null ".

However, in fact, the requirements for recycling an object are not that strict, because FP not only references the counting method, but also includes the mark clearing method. The Mark clearing method starts from the root object of the Program (stage, static attribute, active timer and loader, externalinface. callback) A level-1 traversal object can be recycled even if it does not meet the conditions of reference notation. For example, if two objects reference each other but have no relationship with the outside world, they form an isolated island and can be recycled, even if they reference each other, the reference count is not 0. Compared with reference counting, this method can indeed find the actually idle objects that cannot be accessed again. Therefore, we can see that many people's Code does not actually set null, or even does not have removeeventlistener. It can be recycled normally, and less code can make the program simpler, it will be tiring to meet all the criteria for Mark clearing.

"Cannot be accessed by the root", which is ambiguous and cannot be used as a basis for judgment. So I will give a few specific examples to illustrate what kind of situation meets the requirements of the Mark clearing method.

First, it is clear that the mark clearing method is only based on whether the root access can be used as the unique basis, and does not need to pay attention to the number of times referenced. Do not confuse it.

  • Attribute mutual reference is very clear. Generally, an object contains several attributes, so this object can naturally maintain its attribute reference. If this class is not recycled (can be accessed by the root), all its attributes will not be recycled. Similarly, if this class can be recycled (cannot be accessed by the root), it will not hinder the collection of attributes. Therefore, you do not need to set all attributes to null unless you want to reclaim the memory of the attributes when the object exists. This requirement basically does not exist.
  • Static attributes are a special case. Static attributes are the root, so you must set null to recycle them. There is no other way.
  • As for the objects in the display list. Since the root (stage) can use getchildat to access all its sub-objects, as long as you are in the display list, it will certainly not be recycled. However, if the parent-layer object of the display object is no longer displayed in the list, its sub-objects do not matter even if they are still in the parent-layer object, because it cannot be accessed by stage. Therefore, you do not need all objects at the removechild layer, but only need the parent object at the highest level of removechild.
  • A. addeventlistener ("Event", B. handler), after adding events like this, you can consider B. handler becomes an attribute of a (because a can call B when needed. handler), which also complies with the principles of mutual property reference. However, events are indeed more difficult to judge than attributes, because there are many mutual references. There are three possible cases:
    1. Listening to your own events is equivalent to saving your reference with your own properties, which will not prevent you from being recycled in any case.
    2. Listen to your own sub-objects (attributes or child. Because sub-objects are themselves maintaining their references, even if they maintain your references, only one loop is formed. Once you are out of contact with stage, sub-objects will also be out of contact, and of course you cannot prevent yourself from being recycled. Unless sub-objects can be independently referenced for some reason (such as being stored in static attributes), this is rare.
    3. Listen to your parent object (parent or stage) for events. This makes you an attribute of the parent object. As long as the parent or stage is not recycled, you will not be recycled. Especially stage, it will certainly not be recycled. In this case, you may not be able to recycle it. You must removeeventlistener.

In general, it is important to pay attention to the monitoring of stage and parent events. In other cases, the collection will not be blocked. For stage and parent, most of the listeners are mouse and keyboard events. The number is not large. Note that most memory leaks caused by events can be prevented here.

In fact, memory leakage is not easy. According to common programming habits, only listening to stage events can cause unexpected leaks, which can be recycled smoothly. This is much easier than manual memory recovery every time.

Here, only bitmapdata is an exception. In addition to following the above rules, to recycle its memory, you must manually call the dispose method. People who are used to automatic recovery will be tired. You must note that the bitmapdata attribute of a bitmap object needs to be manually destroyed, and the bitmap loaded by loader needs to be manually destroyed. When you use a generated bitmap as a bitmap to fill the tiled image, the bitmap must also be destroyed after the image is destroyed (so you must keep storing the reference of the bitmap ). Bitmapdata is a 32-bit uncompress image. Any one of them will be very large and cannot be recycled properly. A bitmapdata leak can expose tens of thousands of complex objects.

If there is a very obvious memory leak, most of the time it is a bitmap leak. Therefore, before studying the reference counting method and Mark clearing method and GC, please ensure that the bitmap part is not faulty.

Exception when weak reference

Weak references change the garbage collection rules. If a weak reference is used, addeventlistener will not affect object recycling. Even if you add a listener to the stage, it will not recycle itself. However, this is also a disadvantage, because sometimes you want to restrict the collection of objects by referencing, and using weak references will make this object sometimes not recycled. This is rare, but once it appears, it is very difficult to identify such errors that are not easy to reproduce. Therefore, I do not recommend weak references.

There are only two weak references in avm2:

  • One is the 5th attributes of addeventlistener, named userweakreference, set to true, and the listening event will not affect object recycling.
  • One is the constructor parameter of dictionary, which is weakkeys and set to true. when the key is a complex object, the key can still be recycled even if the dictionary exists. Note: The key, not the value, and the value is not subject to weak reference. This attribute is also clearly written as weakkeys.
Memory leakage Search Method

Flash Builder provides a summary analysis tool to help us find memory leaks. Most cases can help us solve the problem. You can view the following article:

Http://blog.csdn.net/bbmjfpig/archive/2010/12/30/6107347.aspx

The key point is that the memory leakage detection should be "Create, sample, destroy, create, sample", and then observe the leakage by comparing the two samples. Because objects will have some cached data when they are created for the first time, they will not be recycled with the destruction of objects, such as class-defined caches, such as skins. They will only be created once, which is not the same as the leakage we see.

Force GC can be executed if necessary

Because each GC consumes performance, the more objects, the slower the GC. I understand that Flash Player disables the released version of system. GC () is used to prevent developers from abusing this method, but sometimes we do need to manually control the GC timing, because if the GC process encounters a large number of recyclable objects, flash player will be stuck.

For example, we need to recycle the memory once when switching the screen, and the card won't be visible at this time, instead of recycling the animation after switching and freezing the animation. Or, we will execute a GC regularly when necessary to share the time required by the GC. Therefore, it is also an option to use the hack method to forcibly execute a GC. Of course, this has nothing to do with Memory leakage.

Flash Player is particularly poorly designed. It does not support step-by-step GC. Once GC, it cannot avoid card problems. The GC timing is not controlled yet ......

Trace memory remaining

In the test, there is indeed an infinite increase in memory in flash. The reason is unknown. I threw 0.5 million objects into an array. After destruction, the memory usage will be 1 MB (not if it is not thrown into the array), but the number is small, however, to reach the 50 million m memory, we need objects, which is usually hard to reach.

However, some people say that this is only the performance of object destruction and not all memory is released. In fact, it can still be completely released. Or it is caused by the inaccuracy of totalmemory. I don't know about this.

However, even if this is indeed a Flash Player bug, it is still harmless.

[Transfer] as3 garbage collection

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.