Adobe Flex 3 Help

Testing applications for performance

You can use various techniques to test start-up and run-time performance of your Flex applications, such as monitoring memory consumption, timing application initialization, and timing events. The Flex profiler provides this type of information without requiring you to write any additional code. If you are using Flex Builder, you should use the profiler for testing your application's performance. For more information, see Profiling Flex applications in Using Adobe Flex Builder 3.

Calculating application initialization time

One approach to performance profiling is to use code to gauge the start-up time of your application. This can help identify bottlenecks in the initialization process, and reveal deficiencies in your application design, such as too many components or too much reliance on nested containers.

The getTimer() method in flash.utils returns the number of milliseconds that have elapsed since Adobe® Flash® Player or Adobe AIR™ was initialized. This indicates the amount of time since the application began playing. The Timer class provides a set of methods and properties that you can use to determine how long it takes to execute an operation.

Before each update of the screen, Flash Player calls the set of functions that are scheduled for the update. Sometimes, a function should be called in the next update to allow the rest of the code scheduled for the current update to execute. You can instruct Flash Player or AIR to call a function in the next update by using the callLater() method. This method accepts a function pointer as an argument. The method then puts the function pointer on a queue, so that the function is called the next time the player dispatches either a render event or an enterFrame event.

The following example records the time it takes the Application object to create, measure, lay out, and draw all of its children. This example does not include the time to download the SWF file to the client, or to perform any of the server-side processing, such as checking the Flash Player version, checking the SWF file cache, and so on.

<?xml version="1.0"?>
<!-- optimize/ShowInitializationTime.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" creationComplete="callLater(showInitTime)">
    <mx:Script><![CDATA[
        import flash.utils.Timer;

        [Bindable]
        public var t:String;
        private function showInitTime():void {
            // Record the number of ms since the player was initialized.
            t = "App startup: " + getTimer() + " ms";
        }
    ]]></mx:Script>
    <mx:Label id="l1" text="{t}"/>
</mx:Application>

The executing SWF file for the previous example is shown below:

This example uses the callLater() method to delay the recording of the startup time until after the application finishes and the first screen updates. The reason that the showInitTime function pointer is passed to the callLater() method is to make sure that the application finishes initializing itself before calling the getTimer() method.

For more information on using the callLater() method, see Using the callLater() method.

Calculating elapsed time

Some operations take longer than others. Whether these operations are related to data loading, instantiation, effects, or some other factor, it's important for you to know how long each aspect of your application takes.

You can calculate elapsed time from application startup by using the getTimer() method. The following example calculates the elapsed times for the preinitialize and creationComplete events for all the form elements. You can modify this example to show individual times for the initialization and creation of each form element.

<?xml version="1.0" encoding="iso-8859-1"?>
<!-- optimize/ShowElapsedTime.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
initialize="init()">
    <mx:Script><![CDATA[
        [Bindable]
        public var dp:Array = [
            {food:"apple", type:"fruit", color:"red"}, 
            {food:"potato", type:"vegetable", color:"brown"}, 
            {food:"pear", type:"fruit", color:"green"},
            {food:"orange", type:"fruit", color:"orange"},
            {food:"spinach", type:"vegetable", color:"green"},
            {food:"beet", type:"vegetable", color:"red"}
        ];

        public var sTime:Number;
        public var eTime:Number;
        public var pTime:Number;

        private function init():void {
            f1.addEventListener("preinitialize", logPreInitTime, true);
            f1.addEventListener("creationComplete", logCreationCompTime, true);
        }

        private var isFirst:Boolean = true;

        private function logPreInitTime(e:Event):void {
            // Get the time when the preinitialize event is dispatched.
            sTime = getTimer();
            
            trace("Preinitialize time for " + e.target + ": " + sTime.toString());            
        }

        private function logCreationCompTime(e:Event):void {
            // Get the time when the creationComplete event is dispatched.
            eTime = getTimer();
    
            // Use target rather than currentTarget because these events are
            // triggered by each child of the Form control during the capture
            // phase.
            trace("CreationComplete time for " + e.target + ": " + eTime.toString());
        }
    
    ]]></mx:Script>

    <mx:Form id="f1">
        <mx:FormHeading label="Sample Form" id="fh1"/>
        <mx:FormItem label="List Control" id="fi1">
            <mx:List dataProvider="{dp}" labelField="food" id="list1"/>
        </mx:FormItem>
        <mx:FormItem label="DataGrid control" id="fi2">
            <mx:DataGrid width="200" dataProvider="{dp}" id="dg1"/>
        </mx:FormItem>
        <mx:FormItem label="Date controls" id="fi3">
            <mx:DateChooser id="dc"/>
            <mx:DateField id="df"/>
        </mx:FormItem>
    </mx:Form>
</mx:Application>

The executing SWF file for the previous example is shown below:

Calculating memory usage

You use the totalMemory property in the System class to find out how much memory has been allocated to Flash Player or AIR on the client. The totalMemory property represents all the memory allocated to Flash Player or AIR, not necessarily the memory being used by objects. Depending on the operating system, Flash Player or AIR will be allocated more or less resources and will allocate memory with what is provided.

You can record the value of totalMemory over time by using a Timer class to set up a recurring interval for the timer event, and then listening for that event.

The following example displays the total amount of memory allocated (totmem) to Flash Player at 1-second intervals. This value will increase and decrease. In addition, this example shows the maximum amount of memory that had been allocated (maxmem) since the application started. This value will only increase.

<?xml version="1.0"?>
<!-- optimize/ShowTotalMemory.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" initialize="initTimer()">
    <mx:Script><![CDATA[
        import flash.utils.Timer;
        import flash.events.TimerEvent;

        [Bindable]
        public var time:Number = 0;
        [Bindable]
        public var totmem:Number = 0;
        [Bindable]
        public var maxmem:Number = 0;



        public function initTimer():void {
            // The first parameter is the interval (in milliseconds). The 
            // second parameter is number of times to run (0 means infinity).
            var myTimer:Timer = new Timer(1000, 0);
            myTimer.addEventListener("timer", timerHandler);
            myTimer.start();
        }
        
        public function timerHandler(event:TimerEvent):void {
            time = getTimer()
            totmem = flash.system.System.totalMemory;
            maxmem = Math.max(maxmem, totmem);
        }
    ]]></mx:Script>
    <mx:Form>
        <mx:FormItem label="Time:">
            <mx:Label text="{time} ms"/>
        </mx:FormItem>
        <mx:FormItem label="totalMemory:">
            <mx:Label text="{totmem} bytes"/>
        </mx:FormItem>
        <mx:FormItem label="Max. Memory:">
            <mx:Label text="{maxmem} bytes"/>
        </mx:FormItem>
    </mx:Form>
</mx:Application>

The executing SWF file for the previous example is shown below: