Home / Articles / Profiling Flex Applications in Flex Builder 3 Pro

Profiling Flex Applications in Flex Builder 3 Pro

Article Description

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.

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"
           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();

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.

2. Memory Profiling a Flex Application | Next Section