Using the Memory Profiler tool

Memory Profiler,All tactics, offerings, and apps require memory to save their commands and statistics. As your app runs, it allocates memory for gadgets and techniques in its assigned reminiscence heap. This heap has a restrained however somewhat flexible size. The Android device manages this constrained aid for you by growing or reducing allocatable memory length. The device also frees memory for reuse via doing away with objects which can be not used. If your app makes use of extra reminiscence than the system could make available, the system can terminate the app, or the app may crash.

  • Memory allocation is the manner of booking reminiscence in your app’s items and strategies.
  • Garbage collection is an automated process in which the device frees area in a laptop’s memory by way of casting off data this is now not required, or no longer in use.

Android offers a controlled reminiscence environment. When the system determines that your app is no longer the use of a few gadgets, the garbage collector releases the unused memory again to the heap. How Android finds unused memory is constantly being progressed, however on all Android versions, the gadget ought to at some point in short pause your code. Most of the time, the pauses are imperceptible. However, in case your app allocates memory quicker than the device can collect unused memory, your app is probably not on time whilst the collector frees reminiscence. The postpone may want to reason your app to pass frames and look slow.

Even if your app doesn’t appear gradual, in case your app leaks memory, it may hold that memory even even as inside the background. This behavior can gradual the rest of the machine’s memory overall performance through forcing needless rubbish-series occasions. Eventually, the device is forced to prevent your app system to reclaim the reminiscence. When the person returns on your app, the app ought to restart absolutely.

To help save you these troubles, use the Memory Profiler device to do the following:

  • Look for undesirable memory-allocation patterns within the timeline. These styles is probably inflicting overall performance troubles.
  • Dump the Java heap to see which gadgets are the use of memory at any given time. Dumping the heap numerous instances over an extended duration can help you become aware of memory leaks.
  • Record memory allocations during regular and excessive user interactions. Use this statistics to identify wherein your code is allocating too many or large gadgets in a brief time, or wherein your code isn’t liberating the allocating objects and inflicting a memory leak.

For statistics about programming practices that could reduce your app’s reminiscence use, study Manage Your App’s Memory.

Memory Profiler,What you should already KNOW

You should be able to:

  • Create apps with Android Studio and run them on a mobile device.

Memory Profiler,What you will LEARN

You will learn how to:

  • Use Memory Profiler to collect data about your app.
  • View Memory Profiler reports.
  • Dump the Java heap and inspect it.
  • Record memory allocation data for your app.

Memory Profiler,What you will DO

  • Run Memory Profiler and generate, save, and inspect data.

Memory Profiler,App overview

  • You will run the LargeImages and RecyclerView apps from preceding practicals, the usage of the Memory Profiler.
  • You will run the MemoryOverload app, which creates thousands of views, in the end the usage of up all available memory.

Run the Memory Profiler tool

Android Profiler is a hard and fast of gear that offer actual-time information about your app, along with memory allocation and community usage. You can seize and examine records as your app runs, and keep facts in a document that you could analyze in numerous viewers.

In this practical, you examine the basics of using Memory Profiler to tune down performance troubles and crashes associated with your app’s reminiscence usage.

If you probably did any of the preceding performance tools practicals, your environment is already installation for debugging with the Android Profiler. Otherwise, see the Prerequisites.

Start the Memory Profiler tool with the LargeImages app

  • Open the LargeImages app in Android Studio.
  • Run LargeImages on a device with Developer options and USB Debugging enabled. If you connect a device over USB however do not see the tool listed, ensure that you have enabled USB debugging on the device.

For the next steps, use the screenshot below as a reference.

  • To open the Android Profiler, at the lowest of Android Studio click on the Android Profiler tab (shown as 1 inside the screenshot).
  • Select your device and app, if they’re no longer routinely selected (2 within the screenshot).
  • The Memory graph starts offevolved to show. The graph shows actual-time reminiscence use (three). The x -axis suggests time elapsed, and the y -axis suggests the quantity of reminiscence utilized by your app (four).
  • In the app, switch the images to peer the Memory graph exchange.
  • Click in the Memory graph, and the graph expands and separates into memory sorts. Each reminiscence kind (inclusive of Java, Native, and Graphics) is indicated with a exclusive color in a stacked graph. Check the important thing along the top of the graph to match colours and memory types.

Read about the Memory Profiler tool

Familiarize your self with the Memory Profiler consumer interface, panes, and functions with the assist of the annotated screenshot beneath. Not all of those tools are open when you begin Memory Profiler.

The Memory Profiler panes and features that you use in this practical are shown in the screenshot, as follows:

  • (1) Force garbage collection. Small Trash icons in the graph imply garbage-series events that you or the device precipitated.
  • (2) Capture a heap unload and show its contents.
  • (3) Record memory allocations and show the recorded information.
  • (4) The highlighted portion of the graph shows allocations which have been recorded. The purple dots above the graph suggest consumer actions.
  • (5) Allocation-recording and heap-unload results appear in a pane beneath the timeline. This instance indicates the reminiscence allocation results all through the time indicated within the timeline.
  • (5 and six) When you view both a heap unload or reminiscence allocations, you may choose a category name from this listing (five) to view the listing of instances at the right (6).
  • (7) Click an instance to open an extra pane. When you are viewing the allocation record, the extra pane shows the stack hint for in which that reminiscence become allocated. When you’re viewing the heap sell off, the extra pane indicates the remaining references to that object.

See the Memory Profiler documentation for a full list of controls and features.

Run Memory Profiler for the MemoryOverload app

A reminiscence leak is while an app allocates reminiscence this is by no means freed, even after the reminiscence is no longer wanted. A memory leak can happen while an app allocates many gadgets and does now not loose unused or dereferenced objects. Memory leaks can slow down an app or in the worst case, eventually make the app crash. Finding and fixing reminiscence leaks is a lot less difficult when you have a device that indicates you what is occurring with the reminiscence that your app is the usage of.

To exhibit a memory leak, the MemoryOverload app creates and hundreds hundreds of TextView gadgets at the tap of a button. When you run the app and monitor it with Memory Profiler, you see a graph that indicates an increasing number of memory being allocated. Eventually, the app runs out of memory and crashes.

  • Download the MemoryOverload app.
  • Run the app.
  • In Android Studio, open the Android Profiler. Click within the Memory graph to peer the detail view for Memory Profiler.
  • In the app, tap the floating motion button (+). Wait till the app is performed adding the perspectives to the display screen. This may take a while. In Memory Profiler, have a look at how the app is the use of greater reminiscence as views are added.
  • Tap the + button some extra times. Your app will generate a graph similar to the only shown below. The graph indicates increasingly reminiscence used and few, small, or no rubbish-collection events. This allocation-graph pattern can indicate a memory leak. (The graph can appearance very extraordinary for exceptional gadgets.)
Note:You may also word a put off among tapping the plus button and the next batch of perspectives being added. To see just how lengthy it takes, run the Profile GPU Rendering tool, which you permit from inside your device’s Developer options settings.
  • Keep adding views till the app crashes and suggests an Application Not Responding (ANR) conversation. Logcat presentations a message like this one:
03-24 13:05:05.226 10057-10057/com.example.android.memoryoverload A/libc: Fatal signal 6 (SIGABRT), code -6 in tid 10057 (.memoryoverload)

SIGABRT is the sign to provoke abort() and is normally called by using library features that detect an internal errors or a few significantly broken constraint.

  • After overloading and crashing your device, it is a good idea to remove the app from your device and restart your device.

The MemoryOverload app is a made-up instance to expose a pattern, and it does no longer comply with nice practices! However, allocating and not releasing perspectives is a commonplace purpose of memory problems. See the Memory and Threading video for more on this topic.

One repair for the MemoryOverload app might be to not create perspectives that aren’t visible at the screen. A 2nd answer could be to mix perspectives. Instead of creating a view for every rectangle in a row, you may create a patterned background of rectangles and display multiple rectangles in a single view.

Run Memory Profiler for RecyclerView

  • Run the RecyclerView app.
  • In the app, scroll through the items even as Memory Profiler is open.
  • Click the floating movement button (+) to add loads greater listing gadgets You may also see changes in memory allocations and some spikes in the graph.
  • Scroll through all the gadgets once more. Notice that the memory bar is flat while you are scrolling. RecyclerView is a good way of displaying lists, due to the fact perspectives that end up invisible are reused to show new content because the list is scrolled.

Dump and inspect the app heap

Dump the Java (app) heap

  • Run the MemoryOverload app.
  • In Android Studio, open the Android Profiler.
  • Click the Memory graph to fill the Android Profiler pane with the exact view.
  • In the MemoryOverload app, faucet the floating action button (+) as soon as to add a set of views. Wait for the row of perspectives to seem.
  • In Android Studio, click the Dump Java Heap button Dump Java Heap button to capture the app heap into a report and open the listing of classes. This can take a long term. The Heap Dump pane will open after the heap unload is whole.

Inspect the dumped heap

Do the subsequent to open all the facts panes, then talk to the screenshot annotations for an evidence of every pane.

  • In the Heap Dump pane (1), find and click the TextView elegance. This opens an Instance View pane.
  • In the Instance View pane (2), click on one of the TextView times. This opens a References pane (3). Your display have to now appearance much like the screenshot below.

He Heap Dump pane (1) indicates all of the lessons related to your app, as they’re represented at the heap. The columns give you length records for all of the gadgets of this magnificence. Click a column header to kind by way of that metric.

  • Allocation Count: Number of times of this elegance which are allocated.
  • Shallow Size: Total size of all instances of this magnificence.
  • Retained Size: Size of reminiscence that every one times of this elegance are dominating.

After you click the floating motion button (+) within the MemoryOverload app, you see a big range of TextView times on the display screen. Corresponding allocations are recorded at the graph and within the allocation remember for the TextView class.

The Instance View pane (2) lists all the instances of the chosen TextView class which are at the heap. The columns are as follows.

  • Depth: Shortest number of hops from any rubbish-series root to the selected instance.
  • Shallow Size: Size of this example, in bytes.
  • Retained Size: Total length of reminiscence being retained because of all times of this class, in bytes.

The References pane (3) shows all of the references to the chosen instance. For example, within the MemoryOverload app, all of the views are created and introduced to the view hierarchy. When you are debugging an app, search for instructions and instances that must not be there, and then test their references.

For instance, in case you are offloading paintings to some other thread, it is viable that references to perspectives or activities continue to be after an Activity has been restarted, leaking memory on every configuration exchange. Look for long-lived references to Activity, Context, View, Drawable, and other objects that would hold a connection with the Activity or Context field.

Right-click a category or instance and pick Jump to Source. This opens the supply code, and you could look at it for capability troubles.

Click the Export button Export heap unload button on the pinnacle of the Heap Dump pane to export your snapshot of the Java heap to an Android-precise Heap/CPU Profiling document in HPROF format. HPROF is a binary heap-sell off layout initially supported by J2SE. See HPROF Viewer and Analyzer in case you want to dig deeper.

See Memory Profiler, Processes and Threads, and Manage Your App’s Memory.

Record memory allocations

Dumping the heap gives you a photograph of the allotted reminiscence at a particular factor in time. Recording allocations shows you how memory is being allotted over a time period.

 Record allocations

  • Run the MemoryOverload app.
  • In Android Studio, open the Android Profiler.
  • Click the Memory graph to fill the Android Profiler pane with the distinct view.
  • Click the Record Memory Allocations button The Record Memory Allocations button .
  • On your tool with the MemoryOverload app running, tap the floating movement button (+) to feature a hard and fast of views.
  • Wait just a few seconds, then click on the Record Memory Allocations button again. The button is now a black square The button to forestall recording memory allocations indicating that clicking it’ll pause the recording. Don’t wait too long to pause the recording, due to the fact the recorded documents can get huge.

Inspect recorded allocations

Refer to the screenshot below for the next steps.

  • The Memory graph shows which element changed into recorded (1). Select the recorded portion, if vital. You can record a couple of section of the graph and transfer among them.
  • As inside the previous challenge, the Heap Dump pane (2) suggests the recorded facts.
  • Click a class name to see times allotted in the course of this period of time (three). As within the preceding project, there ought to be many times of the TextView class.
  • Click an instance to see its Call Stack (4).
  • At the top of the Call Stack (that’s truely the lowest…) is the approach name for your code that initiated introduction of this instance. In this case, the technique is addRowOfTextViews().

Click addRowOfTextViews to locate this call in your code (5).

To export the recordings to an hprof file (for hundreds) or an alloc record (for allocations), click on the Export button Heap window export button inside the top-left corner of the Heap Dump or Allocations pane. Load the document into Android Studio later for exploration.

Summary

  • Use Memory Profiler to observe how your app uses memory over time. Look for styles that suggest memory leaks.
  • Use Java heap dumps to become aware of which classes allocate big quantities of memory.
  • Record allocations over the years to study how apps allocate reminiscence and where to your code the allocation is happening.