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

Home > Articles > Web Design & Development

Like this article? We recommend

Like this article? We recommend

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.

  1. Choose File > New > Flex Project. Use ProfilerTest for the project name.
  2. Set the project location as flex3tfs/Lesson26/profiler/start.
  3. For the application type, select Web application.
  4. Set the Server technology to None, and then click Next.
  5. Leave the Output folder as bin-debug, and click Next.
  6. Leave the Main source folder as src. Click the Browse button for the Main application file, select ProfilerTest.mxml, and click OK.
  7. Click Finish. You have created a project to run the application for profiling practice.
  8. Run the ProfilerTest.mxml application.
  9. Click one of the categories on the left. The products should appear on the right (see Figure 6).
  10. 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.
  11. Click several more categories. Notice the momentary pause that occurs each time you click a category before the new products display onscreen.
  12. Close the browser and return to Flex Builder.
  13. 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.

  1. 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.

  2. 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.

  3. Click Resume. The Eclipse perspective changes to Flex Profiling.
  4. 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.

  5. 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.

  6. 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.

  7. 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.

  8. 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.

  9. 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.

  10. 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.
  11. 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.

  12. 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.

  13. 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.

  14. 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.

  15. 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. 16. Examine several of the other ImageDisplay class instances. Each will show a similar result, with a reference from UpdateManager.
  17. 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.
  18. 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.

  1. Switch back to the Flex Development perspective in Flex Builder and open the ImageDisplay.mxml class.
  2. 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.

  3. 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.

  4. Save ImageDisplay.as.
  5. Profile your application again, using the same settings.
  6. Once the application has launched, click each of the product categories to see all of the products.
  7. 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.

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