Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Web Design & Development

Profiling Flex Applications in Flex Builder 3 Pro

  • Print
  • + Share This
In this excerpt from Adobe Flex 3: Training from the Source, the authors explain memory profiling and performance profiling, two highly useful optimization techniques facilitated by the new Profiler feature in Flex Builder 3 Pro.
Like this article? We recommend

Like this article? We recommend

This article teaches you about the tools and techniques used to identify a set of problems that don’t prevent a Flex application from functioning immediately, but rather cause the application to run more slowly or use more memory than it should.

We’ll discuss memory profiling and performance profiling, two techniques facilitated by the new Profiler feature in Flex Builder 3 Pro. To understand the need for this tool, you need to learn some details about how Flash Player executes code in Flex and how it allocates (gives) and frees (takes back) memory.

Flash Player Memory Use

This article deals with a lot of memory-related issues. The process of memory and garbage collection can be immensely difficult to understand completely. However, it’s necessary to have at least a high-level understanding to use the Flex Profiler as an effective tool, so we’ll discuss these issues in a simplified way that’s intended to provide some understanding rather than convey complete technical correctness.

Flash Player Memory Allocation

Flash Player is responsible for providing memory for your Flex application at runtime. When you execute a line of code that creates a new instance of the DataGrid class, Flash Player provides a piece of memory for that instance to occupy. Flash Player in turn needs to ask your computer’s operating system for memory to use for this purpose.

The process of asking the operating system for memory is slow, so Flash Player asks for much larger blocks than it needs, and keeps the extra available for the next time the application requests more space. Additionally, Flash Player watches for memory that’s no longer in use, so that it can be reused before asking the operating system for more.

Passing by Reference or Value

There are two broad groups of data types that you need to understand when dealing with Flash Player memory:

  • Primitive data types such as Boolean, int, Number, String, and uint are passed by value during assignment or function calls.
  • Objects are passed by reference.

Running the following example of primitives would create two numbers and assign their values separately:

var a:Number;
var b:Number;
a = 5;
b = myAge;
a = 7;

From a very high level, Flash Player memory for this example would look like Figure 1.

By contrast, running the following example would create a single Object instance with two references (ways to find the object):

var a:Object;
var b:Object;
a = new Object();
a.someVar = 5;
b = a;
b.someVar = 7;

From a very high level, Flash Player memory for this example would look like Figure 2.

This point is so important that it’s worth a walkthrough of the code:

  1. First we create two variables named a and b. Both variables are of type Object.
  2. We create a new Object instance and assign it to the variable a. It can now be said that a refers to the new object. When we set a.someVar to the value 5, we’re setting that property inside the object to which a refers.
  3. We assign a to b. This doesn’t make a copy of the object, but simply ensures that a and b refer to the same object.
  4. Finally, when we set b.someVar to the value 7, we’re setting that property inside the object to which both a and b refer. Because a and b both refer to the same object, a.someVar is the same as b.someVar.

Flash Player Garbage Collection

Garbage collection is a process that reclaims memory no longer in use, so that it can be reused by the application—or, in some cases, given back to the operating system. Garbage collection happens automatically at allocation, which can be confusing to new developers. This means that garbage collection doesn’t occur when memory is no longer in use, but rather when the application asks for more memory. At that point, the process responsible for garbage collection, called the garbage collector, attempts to reclaim available memory for reallocation.

The garbage collector follows a two-part procedure to determine which portions of memory are no longer in use:

  1. Reference counting
  2. Mark and sweep

Understanding this procedure will give you the insight necessary to develop applications that use memory appropriately and to understand the information presented by the Flex profiler.

The two parts of the garbage collection process rely on different methods of ensuring that the memory in question is no longer referenced by other objects in use.

As we demonstrated earlier, when you create a new object you usually also create a reference to that object. In the following code snippet, we create a reference named canvas to our new Canvas instance and one named lbl to our newly created Label. We also add the Label as a child of the Canvas.

var canvas:Canvas = new Canvas();
var lbl:Label = new Label();
canvas.addChild( lbl );

All components also maintain a reference to their children, and all component children maintain a reference to their parent. The references from this code snippet look like Figure 3.

This snippet demonstrates at least four references that we need to keep in mind:

  • canvas is a reference to an instance of Canvas.
  • lbl is a reference to an instance of Label.
  • lbl.parent is a reference to the Canvas instance.
  • canvas.getChildAt(0) returns a reference to the Label instance.

The application in Listing 1 illustrates how both parts of the garbage collection procedure determine what’s free for collection.

Listing 1

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
       creationComplete="onCreation(event)">
    <mx:Script>
       <![CDATA[
           import mx.controls.TextInput;
           import mx.controls.Label;
           import mx.controls.ComboBox;
           import mx.containers.Canvas;
           import mx.controls.DataGrid;
           import mx.containers.VBox;
           import mx.containers.HBox;

           private function onCreation( event:Event ):void {
              var hBox:HBox = new HBox();

              var vBox:VBox = new VBox();
              vBox.addChild( new DataGrid() );
              vBox.addChild( new ComboBox() );

              hBox.addChild( vBox );
              this.addChild( hBox );
              
              var canvas:Canvas = new Canvas();
              canvas.addChild( new Label() );
              
              var textInput:TextInput = new TextInput();
           }
       ]]>
    </mx:Script>
</mx:Application>

Let’s walk through the application:

  1. The application calls the onCreation() method when the creationComplete event occurs.
  2. This method creates a new HBox, with a VBox inside it. The VBox contains a DataGrid and a ComboBox instance.
  3. The HBox is added as a child of the application.
  4. A Canvas instance is created, with a Label instance as a child.
  5. Finally, a TextInput is instantiated.

Figure 4 shows the important references just before exiting the onCreation() method.

The diagram shows the references created in the onCreation() method, including the variables canvas, lbl, hBox, vBox, and textInput. However, these variables are defined within the onCreation() method. This means that the variables are local to the method: Once the method finishes execution, those references will disappear, but the objects created within this method will continue to exist.

As mentioned previously, references are the metric that the garbage collector uses to determine the portions of memory that can be reclaimed. If the developer doesn’t have a reference to an object, he or she has no way to access the object or its properties. If there’s no way to access the object, the garbage collector reclaims the memory it used to occupy.

The first method that the garbage collector uses to determine whether references to an object exist is called reference counting. Reference counting is the simplest and fastest method to determine whether an object can be collected. Each time you create a reference to an object, Flash Player increments a counter associated with the object. When you remove a reference, the counter is decremented. If the counter value is zero, the object is a candidate for garbage collection.

In the code in Listing 1, the only object with a zero reference count is the TextInput. After the onCreation() method is completed, the TextInput is left without any references. Remember that if there’s no way to reference an object, the object may be collected.

This example also reveals a problem with reference counting: circular references. If you examine the Canvas and Label, each has a reference to the other, meaning that each has a reference count greater than zero. However, there are no other references to either of these components in the application. If Flash Player could identify this fact, the memory for both of these components could be reclaimed. This is the reason for the second method used within the garbage collection procedure, called mark and sweep.

Using this method, Flash Player starts at the top level of your application and marks each object to which it finds a reference. It then recurses down into each object and repeats the process, continuing to dive further until it runs out of objects to mark. At the end of this process, neither the Canvas nor the Label would be marked, and both would become candidates for garbage collection. Although this method produces definitive results, it’s very slow compared to reference counting, so it isn’t run continually. Working together, these two methods can be used to achieve higher levels of performance and garbage collection accuracy.

Garbage Collection

Now that you understand how garbage collection decides when to reclaim memory, you can begin to establish practices to let the garbage collector do its job. Simply stated, you need to ensure that you remove all references to an object when you no longer need that object. Leaving an accidental reference to an object prevents that memory from being reclaimed; the inability to reclaim this memory can cause memory usage to continue to grow as the application continues to execute. This situation is commonly referred to as a memory leak.

Visual children are added to components by using the addChild() method. Children can also be removed by using either of the following methods:

  • removeChild() requires you to provide your own reference to the child needing removal, such as removeChild(hBox).
  • remoteChildAt() allows you to specify the index of the child within its parent, removeChildAt(0). This method simply uses the reference maintained by the parent to identify the child.

Both methods ensure that both the parent and child references are cleared from within the components.

In the example in Listing 1, if you removed the HBox from the application with the removeChild() method, the HBox and every other object contained within it would become available for collection, as there are no other references to the child. However, there is a caveat: There are other ways in which references are created and maintained, in addition to the variables and properties we’ve discussed so far.

Understanding Leaks Caused by Event Listeners

The most common cause of memory leaks when programming in Flex is the use of event listeners without proper care. You probably are aware that the addEventListener() method allows you to listen programmatically to an event being broadcast. We need to dive a little deeper into this concept and develop a high-level model of this functionality to understand its implications for garbage collection.

Objects that want to be notified when an event occurs register themselves as listeners. They do this by calling the addEventListener() method on the object that broadcasts the event (called the broadcaster or dispatcher). The following example shows a simple case:

var textInput:TextInput = new TextInput();
textInput.addEventListener(’change’, handleTextChanged);

In this case, the TextInput is expected to broadcast an event named change at some point in the future, and you want the handleTextChanged method to be called when this situation occurs.

When you call addEventListener() on the TextInput instance, it responds by adding a reference to the object (the one that contains the handleTextChanged method) to a list of objects that need to be notified when this event occurs. When it’s time to broadcast the change event, the TextInput instance loops through this list and notifies each object that registered as a listener.

In memory, this looks something like Figure 5.

The important thing to take away from this discussion is that each object that broadcasts an event maintains a reference to every object listening for the event to be broadcast. In terms of garbage collection, this means that, in certain circumstances, if an object is listening for events it may never be available for garbage collection.

Your main weapon to combat this problem is diligence. In much the same way that any child added with addChild() can be removed with removeChild(), addEventListener() has a parallel function named removeEventListener() that stops listening for an event. When removeEventListener() is called, it also removes the reference to the listener kept by the broadcaster, potentially freeing the listener for garbage collection.

In an ideal world, the number of addEventListener() and removeEventListener() calls in your application should be equal. However, sometimes you’ll have less control over when objects are no longer needed, and using removeEventListener() simply isn’t feasible. Shortly, you’ll see an example of such a situation. In these instances, we can use a concept called weak references.

Using Weak References with Listeners

Like most of the items we’ve discussed so far, weak references are an advanced topic that requires quite a bit of understanding to use correctly. Instead of covering this topic completely, we’ll just explain the high-level portions that are important in this context.

When adding an event listener to a broadcaster, the developer can specify that the event listener should use weak references. This is accomplished by specifying extra parameters for the addEventListener() method:

var textInput:TextInput = new TextInput();
textInput.addEventListener(’change’, handleTextChanged, false, 0, true);

You probably have used the first two parameters of the addEventListener() method: the name of the event and the method to call when the event occurs. However, three other parameters can be specified, in this order:

  • Whether the event listener should use capture
  • Its priority relative to other listeners for this event
  • Whether weak references should be used

The first two parameters are beyond the scope of this lesson, but the last one is critical to garbage collection.

Specifying a value of true (the default is false) for the fifth parameter of the addEventListener() method specifies that the reference established by this listener is to be considered weak. All the references that we’ve discussed so far are considered strong references, which we’ll simply say are references considered by the garbage collector when deciding whether an object is available for collection. Conversely, weak references are ignored by the garbage collector, meaning that an object with only weak references will be collected.

As a more concrete example, if an object has a strong reference and three weak references to it, it can’t be collected as garbage. However, if the strong reference is removed, the weak references would be ignored, and the object could be collected.

In practice, this means that specifying the weak reference flag on addEventListener() calls is almost always a good practice. It prevents the case where listening to an event is the only reason that an object is not collected.

  • + Share This
  • 🔖 Save To Your Account

Peachpit Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from Peachpit and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about Peachpit products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites; develop new products and services; conduct educational research; and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email ask@peachpit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by Adobe Press. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.peachpit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020