Sometimes it’s nice to keep an eye on the memory of an application without involving the Flash Builder profiler. This post demonstrates a simple and lightweight component that graphs the value of the Flash Player’s System.totalMemory over time. The chart can be very useful for noticing spikes in memory that might require further investigation with the profiler.
BasicMemoryGraph extends from Group and contains two Labels for the peak memory and the current memory. It also contains a Path that visually represents the memory. The <fx:Script> section of the graph contains the properties and methods that drive the component. The component itself is a graph where the bottom corresponds to 0mb and the top corresponds to the largest amount of memory that the component has seen.
BasicMemoryGraph has two properties,
numPoints. You can set
frequency to change the time (in milliseconds) in between calls to System.totalMemory. The default is 1000ms (or 1 second). Also, you can set
numPoints to change the number of points plotted on the graph. The default is 100 points.
If we take a closer look at the code, we see that our Timer calls the function
frequency milliseconds. The method,
addMemPoint(), checks System.totalMemory and adds it as a new point to the underlying array while also updating the text of the labels. It then invalidates the display list which brings us to the method,
drawPath(). The method,
drawPath(), populates the data for the path by calculating the x and y positions of each memory point based on the size of the component.
But enough coding, I’ve included a small example below. It contains two Lists (one with virtual layout and one without), a couple of buttons to add and remove a random number of items from each list, and 2 versions of the memory graph on the bottom. The first version is the BasicMemoryGraph described above, and the second is an improvement on the first called MemoryGraph.
Here is the example:
As you might have noticed, the second graph has a few more features and also, a few more properties than the BasicMemoryGraph. The MemoryGraph component adds the triangle “sliders” and the properties: minMem, maxMem and maxGraphValue. The triangle slider thumbs allow you to control the min and the max of the graph also known as minMem and maxMem. The largest value that maxMem may have is dependent on the maxGraphValue. All of these values are in megabytes (mb). I have also done a few optimizations to improve memory usage and performance including a circular array and removing redundant path points to limit the size of the path string.
Analysing memory in Flash Player can be tricky, be sure to read more on the subject at Alex Harui’s blog, for example this post.
Note: This sample requires Flex SDK 126.96.36.19951 or higher. You can get the latest SDK builds from opensource.adobe.com.