- Flash Player Memory Use
- Memory Profiling a Flex Application
- Performance Profiling a Flex Application
Memory Profiling a Flex Application
Memory profiling involves examining the memory used—as well as the memory currently in use—by objects in your application. Those objects could be simple classes, such as Strings, or complex visual objects, such as DataGrids. Using memory profiling, you can determine whether an appropriate number of objects exist and whether those objects are using an appropriate amount of memory.
Reviewing the ProfilerTest Application
In this exercise, you’ll use a new sample project that has been poorly designed, with memory leaks and performance issues. Using the Flex Builder Profiler, you’ll learn the basic interface and identify a memory leak caused by an event listener issue. Then you’ll fix the issue and verify the results with the Profiler.
- Choose File > New > Flex Project. Use ProfilerTest for the project name.
- Set the project location as flex3tfs/Lesson26/profiler/start.
- For the application type, select Web application.
- Set the Server technology to None, and then click Next.
- Leave the Output folder as bin-debug, and click Next.
- Leave the Main source folder as src. Click the Browse button for the Main application file, select ProfilerTest.mxml, and click OK.
- Click Finish. You have created a project to run the application for profiling practice.
- Run the ProfilerTest.mxml application.
- Click one of the categories on the left. The products should appear on the right (see Figure 6).
- Click the Toggle View Only button below the categories. The Add to Cart button in each of the products should toggle between visible and hidden as you click this button.
- Click several more categories. Notice the momentary pause that occurs each time you click a category before the new products display onscreen.
- Close the browser and return to Flex Builder.
- Open the following files inside Flex Builder:
- src/managers/UpdateManager.as
- src/component/ImageDisplay.mxml
- src/ProfilerTest.mxml
At this point, you know enough Flex and ActionScript to look through this code on your own. Here’s a brief high-level description of the code and the interaction of the objects. Using this description, review the code and make sure that you can identify all of the major points.
- UpdateManager.as. Sometimes you want to ensure that only one
instance of a specific object exists in an application. For example, there can
be only one <mx:Application> tag in any Flex application. The
UpdateManager is one of these objects. We want to make sure that we
create just one UpdateManager and that every object in the system uses
this single instance, so it follows a specific design pattern called the
singleton pattern. The details of this pattern and how it works are
inconsequential to this lesson. It’s just important to understand that
there will be only one UpdateManager in the entire application at any
time.
The UpdateManager’s job is to broadcast an event called toggleViewOnly to its listeners whenever the UpdateManager’s toggleViewOnly() method is called.
- ImageDisplay.mxml. This class defines each of the boxes that
display product information on the right side of the screen. It displays
critical information, such as the product name and price, and defines the Add to
Cart button, which is hidden initially.
Each ImageDisplay has a bindable public property called product, which contains information about the product being displayed. It also listens to the UpdateManager’s toggleViewOnly event and responds by changing the visible state of the Add to Cart button.
- ProfilerTest.mxml. This is the main application for your profiling
tasks. It has a VBox with images for each category of food product on
the left side and a repeater tag that displays several ImageDisplay
instances, depending on the selected category.
When a category image is clicked, the handleNavClick() method is called and passed the name of the category. The handleNavClick() method constructs a filename based on the category and calls loadNewXMLData to load that XML file, using an HTTPService. If the data loads successfully, the result is passed to the dataProvider of the repeater, which creates the appropriate number of ImageDisplay instances and passes each instance its data via the public product property.
When the Toggle View Only button is clicked, the toggleViewOnly() method of the UpdateManager is called to notify its listeners.
Profiling the ProfilerTest Application
In this exercise, you’ll use the memory profiling capabilities of the Flex Profiler to identify a memory leak in the ProfilerTest application. You’ll capture and review memory snapshots, identify reference relationships between objects, and determine the object responsible for the memory leak.
- Click the Profile Application button (immediately to the right of the debug
button, as shown in Figure 7).
The application begins launching, but focus then returns to the Flex Builder window and a Configure Profiler window appears.
- Make sure that all of the following options are selected, as shown in Figure
8:
- Enable memory profiling
- Watch live memory data
- Generate object allocation stack traces
Memory profiling will slow your application drastically as the application collects a significant amount of data about when, where, and how often objects are created. These options should be selected only when attempting to diagnose a memory leak or verify that no leak exists.
- Click Resume. The Eclipse perspective changes to Flex Profiling.
- Examine the screen. The Profiling perspective begins displaying
information regarding memory usage, cumulative and current object instances, and
cumulative and current memory use for each object type (see Figure 9).
The upper-left corner of the screen shows the application being profiled. This area also shows memory snapshots (a concept we’ll explore shortly), and several icons at upper right that you’ll learn how to use momentarily.
The upper-right corner shows a graph of current memory usage along with peak memory usage. One clear indicator of a memory leak in an application is that the memory never truly peaks. If your application grows with continued use over time, you likely have a memory leak.
The bottom of the screen currently contains a view called Live Objects. This view shows the class, package, and cumulative and current instances of each object type, as well as the cumulative and current memory used by those objects.
On the right side of the screen, at the same level as the Live Objects tab, are a series of icons that we’ll explore shortly.
- Switch to your web browser running the ProfilerTest application, and click
the Dairy category.
With memory profiling enabled, the entire application moves much more slowly than before.
- Once the products from the Dairy category appear on the right, switch back
to Flex Builder and look at the Live Objects view. The ImageDisplay
class should be listed in the far-left column. The cumulative instances and the
instances should both show 3.
When you clicked the Dairy category, the application created a new HTTPService and loaded XML data for this category. The data was then passed to the repeater’s dataProvider property, which created an instance of the ImageDisplay for each product in the category.
The Cumulative Instances column shows the total number of times this class has been instantiated since the application started. The Instances column shows the number of instances that are still in memory. The difference between the Cumulative and Instances column is the number of instances that have been garbage collected at some point.
- Click through each of the other categories in the application to display the
products contained within them. Switch back to the Flex Profiler and view the
instance information for the ImageDisplay class.
The ImageDisplay class now shows 18 cumulative and current instances; none of these instances have been garbage collected yet, which could indicate a memory leak.
- Directly above the column named Memory in the Live Objects grid are a series
of icons arranged horizontally. The first of these icons (see Figure 10) causes
the garbage collector to execute immediately. Click this icon now.
As mentioned earlier, garbage collection runs automatically during allocation; however, it may be difficult for you to understand precisely when garbage collection last ran. The Flex Profiler gives you the ability to run garbage collection as needed.
- Review the cumulative and current instances for the ImageDisplay
class again.
The number of instances is now 18. As you just forcibly ran garbage collection, and there are only three ImageDisplay instances displayed onscreen currently, it seems certain that there’s a problem: ImageDisplay instances that are no longer used are not being garbage collected. As you learned earlier, the only thing that would prevent garbage collection is a remaining reference to these ImageDisplay instances.
- Click the icon immediately to the right of the garbage collection icon (see Figure 11) to take a memory snapshot. A memory snapshot saves the current state of memory at the moment you click the snapshot button. The snapshot doesn’t update the Live Object view, but allows you to analyze the memory in a much deeper way.
- Double-click the words Memory Snapshot underneath your running
application in the upper-left corner of the window.
After analyzing the data, a new tab opens next to the Live Object tab, displaying the snapshot information. It’s possible to take multiple snapshots and even save this data for review as you attempt to resolve problems within your application. Figure 12 shows the results of a new memory snapshot.
- On the Memory Snapshot tab, double-click the ImageDisplay
class.
There are 18 separate listings for each of the ImageDisplay objects in memory when this snapshot was taken, each with a number in parentheses. The number in parentheses is the total number of references to the current object.
- Click the first component:ImageDisplay label.
The right side of the screen shows the allocation trace. This information shows where in the program flow this object was first created. In this case, this particular object was created in a method in Container.as, which was called from Repeater.as, which was called from ProfilerTest.mxml. The line number of each of these calls is also recorded.
At this point, you know that the object was created because of the Repeater call, which is correct, but you don’t know which other object has a reference that’s preventing this object from being garbage collected.
- Expand the component:ImageDisplay label to show all objects in
the system that contain references to the current object and the property name
within that object that holds the reference. This list can be extensive.
Remember that many circular references between parent and child are not factors
during the mark and sweep phase of garbage collection, so we’re looking
for items that could still be a factor.
At this point, we’ll make an assumption. Although there may be memory leaks in the code written and provided by Adobe, it’s unlikely that you can do much about those. The memory leak you’re seeing involves objects written in your code. Therefore, to limit the scope of information we need to search, we’re going to focus on things outside of the Adobe-provided Flex framework. In other words, ignore any objects that exist in the mx.* path.
- Focus your search for references on the remaining items. Open each of
the Function subitems, and examine the children of these references (see Figure
13).
Most of the children say component:ImageDisplay. These references exist mainly as a result of data binding; however, they aren’t of particular interest, as we know the garbage collector can handle circular references. You should also find a listing for managers:UpdateManager and a property of [listener0]. This one is important.
- 16. Examine several of the other ImageDisplay class instances. Each will show a similar result, with a reference from UpdateManager.
- Terminate this profiling session by choosing it in the upper-left corner of the screen and clicking the Stop button, or simply by closing your web browser.
- We don’t intend to save the results; once this session is terminated, click the red X to remove the session information.
At this point, you know that the UpdateManager has a reference to each of the ImageDisplay classes. The profiler also gave you the clue that this reference was due to an event listener. Using this information, you should be able to find the issue quickly.
Fixing the ImageDisplay Class
In this exercise, you’ll fix the memory leak identified in the previous task by modifying the event listener to use weak references.
- Switch back to the Flex Development perspective in Flex Builder and open the ImageDisplay.mxml class.
- Find the code on line 17 that adds an event listener to the
UpdateManager instance.
If you review the remainder of the code in this class, you’ll notice that there’s no removeEventListener() call. As noted earlier, ideally the number of addEventListener() calls should match the number of removeEventListener() calls. In this case, we have limited control and understanding of when our class is no longer needed, so we’re going to opt for making the addEventListener() call use weak references.
- Change the code that adds the event listener to use weak references. The
new line of code should read as follows:
updateManager.addEventListener(’toggleViewOnly’, handleViewOnlyChanged, false, 0, true);
The reference in the UpdateManager instance created for each ImageDisplay will no longer count during garbage collection.
- Save ImageDisplay.as.
- Profile your application again, using the same settings.
- Once the application has launched, click each of the product categories to see all of the products.
- Return to Flex Builder and click the Run Garbage Collector icon. The Live Objects view should now show 18 cumulative instances, but only 3 current instances, meaning that the other 15 have been garbage collected and this memory leak has been fixed.
This section merely touched on the power of the memory profiler. For more information, read "Using the Profiler" in the Flex Builder 3 documentation provided by Adobe.