25
RESTRICTED MORPHO MORPHO RESTRICTED This document and the information therein are the property of Morpho, They must not be copied or communicated to a third party without the prior written authorization of Morpho. Android Code Optimization Techniques (Session 2) 20/11/2014

Android Code Optimization Techniques 2

Embed Size (px)

Citation preview

RESTRICTED MORPHO

MORPHO RESTRICTEDThis document and the information therein are the property of Morpho, They must not be copied or communicated to a third party without the prior written authorization of Morpho.

Android Code Optimization Techniques(Session 2) 20/11/2014

RESTRICTED MORPHO

MORPHO RESTRICTED

2 /

This document and the information therein are the property of Morpho, They must not be copied or communicated to a third party without the prior written authorization of Morpho.

AGENDA

CONFIDENTIAL / February 2014 / CEE - CC India

How Android Manages Memory Sharing Memory Allocating and Reclaiming App Memory Restricting App Memory Switching

How Your App Should Manage Memory Use services sparingly Release memory when your user interface becomes hidden Release memory as memory becomes tight Check how much memory you should use Avoid wasting memory with bitmaps Use optimized data containers Be aware of memory overhead Be careful with code abstractions Use nano protobufs for serialized data Avoid dependency injection frameworks Be careful about using external libraries Optimize overall performance Use ProGuard to strip out any unneeded code Use zipalign on your final APK Analyze your RAM usage Use multiple processes

RESTRICTED MORPHO

MORPHO RESTRICTEDThis document and the information therein are the property of Morpho, They must not be copied or communicated to a third party without the prior written authorization of Morpho.

/01/Sharing Memory

RESTRICTED MORPHO

MORPHO RESTRICTED

4 /

This document and the information therein are the property of Morpho, They must not be copied or communicated to a third party without the prior written authorization of Morpho.

SHARING MEMORY

CONFIDENTIAL / February 2014 / CEE - CC India

In order to fit everything it needs in RAM, Android tries to share RAM pages across processes. It can do so in the following ways:

Each app process is forked from an existing process called Zygote. The Zygote process starts when the system boots and loads common framework code and resources (such as activity themes). To start a new app process, the system forks the Zygote process then loads and runs the app's code in the new process. This allows most of the RAM pages allocated for framework code and resources to be shared across all app processes.

Most static data is mmapped into a process. This not only allows that same data to be shared between processes but also allows it to be paged out when needed. Example static data include: Dalvik code (by placing it in a pre-linked .odex file for direct mmapping), app resources (by designing the resource table to be a structure that can be mmapped and by aligning the zip entries of the APK), and traditional project elements like native code in .so files.

In many places, Android shares the same dynamic RAM across processes using explicitly allocated shared memory regions (either with ashmem or gralloc). For example, window surfaces use shared memory between the app and screen compositor, and cursor buffers use shared memory between the content provider and client.

RESTRICTED MORPHO

MORPHO RESTRICTEDThis document and the information therein are the property of Morpho, They must not be copied or communicated to a third party without the prior written authorization of Morpho.

/02/Allocating and Reclaiming App Memory

RESTRICTED MORPHO

MORPHO RESTRICTED

6 /

This document and the information therein are the property of Morpho, They must not be copied or communicated to a third party without the prior written authorization of Morpho.

ALLOCATING AND RECLAIMING APP MEMORY

Here are some facts about how Android allocates then reclaims memory from your app:

The Dalvik heap for each process is constrained to a single virtual memory range. This defines the logical heap size, which can grow as it needs to (but only up to a limit that the system defines for each app).

The Dalvik heap does not compact the logical size of the heap, meaning that Android does not defragment the heap to close up space. Android can only shrink the logical heap size when there is unused space at the end of the heap. But this doesn't mean the physical memory used by the heap can't shrink. After garbage collection, Dalvik walks the heap and finds unused pages, then returns those pages to the kernel using madvise. So, paired allocations and deallocations of large chunks should result in reclaiming all (or nearly all) the physical memory used. However, reclaiming memory from small allocations can be much less efficient because the page used for a small allocation may still be shared with something else that has not yet been freed

CONFIDENTIAL / February 2014 / CEE - CC India

RESTRICTED MORPHO

MORPHO RESTRICTEDThis document and the information therein are the property of Morpho, They must not be copied or communicated to a third party without the prior written authorization of Morpho.

/03/Restricting App Memory

RESTRICTED MORPHO

MORPHO RESTRICTED

8 /

This document and the information therein are the property of Morpho, They must not be copied or communicated to a third party without the prior written authorization of Morpho.

RESTRICTING APP MEMORY

To maintain a functional multi-tasking environment, Android sets a hard limit on the heap size for each app. The exact heap size limit varies between devices based on how much RAM the device has available overall. If your app has reached the heap capacity and tries to allocate more memory, it will receive an OutOfMemoryError. 

In some cases, you might want to query the system to determine exactly how much heap space you have available on the current device—for example, to determine how much data is safe to keep in a cache. You can query the system for this figure by calling getMemoryClass(). This returns an integer indicating the number of megabytes available for your app's heap. This is discussed further below, under Check how much memory you should use.

CONFIDENTIAL / February 2014 / CEE - CC India

RESTRICTED MORPHO

MORPHO RESTRICTEDThis document and the information therein are the property of Morpho, They must not be copied or communicated to a third party without the prior written authorization of Morpho.

/04/Switching Apps

RESTRICTED MORPHO

MORPHO RESTRICTED

10 /

This document and the information therein are the property of Morpho, They must not be copied or communicated to a third party without the prior written authorization of Morpho.

SWITCHING APPS

Instead of using swap space when the user switches between apps, Android keeps processes that are not hosting a foreground ("user visible") app component in a least-recently used (LRU) cache. For example, when the user first launches an app, a process is created for it, but when the user leaves the app, that process doesnot quit. The system keeps the process cached, so if the user later returns to the app, the process is reused for faster app switching.

If your app has a cached process and it retains memory that it currently does not need, then your app—even while the user is not using it—is constraining the system's overall performance. So, as the system runs low on memory, it may kill processes in the LRU cache beginning with the process least recently used, but also giving some consideration toward which processes are most memory intensive. To keep your process cached as long as possible, follow the advice in the following sections about when to release your references.

CONFIDENTIAL / February 2014 / CEE - CC India

RESTRICTED MORPHO

MORPHO RESTRICTEDThis document and the information therein are the property of Morpho, They must not be copied or communicated to a third party without the prior written authorization of Morpho.

/05/How Your App Should Manage Memory

RESTRICTED MORPHO

MORPHO RESTRICTED

12 /

This document and the information therein are the property of Morpho, They must not be copied or communicated to a third party without the prior written authorization of Morpho.

HOW YOUR APP SHOULD MANAGE MEMORY

You should consider RAM constraints throughout all phases of development, including during app design (before you begin development). There are many ways you can design and write code that lead to more efficient results, through aggregation of the same techniques applied over and over.

You should apply the following techniques while designing and implementing your app to make it more memory efficient.

CONFIDENTIAL / February 2014 / CEE - CC India

RESTRICTED MORPHO

MORPHO RESTRICTEDThis document and the information therein are the property of Morpho, They must not be copied or communicated to a third party without the prior written authorization of Morpho.

/05/01Use services sparingly

RESTRICTED MORPHO

MORPHO RESTRICTED

14 /

This document and the information therein are the property of Morpho, They must not be copied or communicated to a third party without the prior written authorization of Morpho.

USE SERVICES SPARINGLY

If your app needs a service to perform work in the background, do not keep it running unless it's actively performing a job. Also be careful to never leak your service by failing to stop it when its work is done.

When you start a service, the system prefers to always keep the process for that service running. This makes the process very expensive because the RAM used by the service can’t be used by anything else or paged out.

The best way to limit the lifespan of your service is to use an IntentService, which finishes itself as soon as it's done handling the intent that started it.

Leaving a service running when it’s not needed is one of the worst memory-management mistakes an Android app can make.

CONFIDENTIAL / February 2014 / CEE - CC India

RESTRICTED MORPHO

MORPHO RESTRICTEDThis document and the information therein are the property of Morpho, They must not be copied or communicated to a third party without the prior written authorization of Morpho.

/05/02Release memory when your user interface becomes hidden

RESTRICTED MORPHO

MORPHO RESTRICTED

16 /

This document and the information therein are the property of Morpho, They must not be copied or communicated to a third party without the prior written authorization of Morpho.

RELEASE MEMORY WHEN YOUR USER INTERFACE BECOMES HIDDEN

When the user navigates to a different app and your UI is no longer visible, you should release any resources that are used by only your UI. Releasing UI resources at this time can significantly increase the system's capacity for cached processes, which has a direct impact on the quality of the user experience.

To be notified when the user exits your UI, implement the onTrimMemory() callback in your Activity classes. You should use this method to listen for the TRIM_MEMORY_UI_HIDDEN level, which indicates your UI is now hidden from view and you should free resources that only your UI uses.

CONFIDENTIAL / February 2014 / CEE - CC India

RESTRICTED MORPHO

MORPHO RESTRICTEDThis document and the information therein are the property of Morpho, They must not be copied or communicated to a third party without the prior written authorization of Morpho.

/05/03Release memory as memory becomes tight

RESTRICTED MORPHO

MORPHO RESTRICTED

18 /

This document and the information therein are the property of Morpho, They must not be copied or communicated to a third party without the prior written authorization of Morpho.

RELEASE MEMORY AS MEMORY BECOMES TIGHT

During any stage of your app's lifecycle, the onTrimMemory() callback also tells you when the overall device memory is getting low. You should respond by further releasing resources based on the following memory levels delivered by onTrimMemory():

TRIM_MEMORY_RUNNING_MODERATE Your app is running and not considered killable, but the device is running low on memory and the system is

actively killing processes in the LRU cache. TRIM_MEMORY_RUNNING_LOW

Your app is running and not considered killable, but the device is running much lower on memory so you should release unused resources to improve system performance (which directly impacts your app's performance).

TRIM_MEMORY_RUNNING_CRITICAL Your app is still running, but the system has already killed most of the processes in the LRU cache, so you should release all non-

critical resources now. If the system cannot reclaim sufficient amounts of RAM, it will clear all of the LRU cache and begin killing

processes that the system prefers to keep alive, such as those hosting a running service.

CONFIDENTIAL / February 2014 / CEE - CC India

RESTRICTED MORPHO

MORPHO RESTRICTEDThis document and the information therein are the property of Morpho, They must not be copied or communicated to a third party without the prior written authorization of Morpho.

/05/04Check how much memory you should use

RESTRICTED MORPHO

MORPHO RESTRICTED

20 /

This document and the information therein are the property of Morpho, They must not be copied or communicated to a third party without the prior written authorization of Morpho.

CHECK HOW MUCH MEMORY YOU SHOULD USE

As mentioned earlier, each Android-powered device has a different amount of RAM available to the system and thus provides a different heap limit for each app. You can call getMemoryClass() to get an estimate of your app's available heap in megabytes. If your app tries to allocate more memory than is available here, it will receive an OutOfMemoryError.

In very special situations, you can request a larger heap size by setting the largeHeap attribute to "true" in the manifest <application> tag. If you do so, you can call getLargeMemoryClass() to get an estimate of the large heap size.

CONFIDENTIAL / February 2014 / CEE - CC India

RESTRICTED MORPHO

MORPHO RESTRICTED

21 /

This document and the information therein are the property of Morpho, They must not be copied or communicated to a third party without the prior written authorization of Morpho.

TIPS Avoid wasting memory with bitmaps

When you load a bitmap, keep it in RAM only at the resolution you need for the current device's screen, scaling it down if the original bitmap is a higher resolution. Keep in mind that an increase in bitmap resolution results in a corresponding (increase2) in memory needed, because both the X and Y dimensions increase.

Use optimized data containers Take advantage of optimized containers in the Android framework, such as SparseArray, SparseBooleanArray, and

LongSparseArray. The generic HashMap implementation can be quite memory inefficient because it needs a separate entry object for every mapping. Additionally, the SparseArray classes are more efficient because they avoid the system's need to autobox the key and sometimes value (which creates yet another object or two per entry). And don't be afraid of dropping down to raw arrays when that makes sense.

Be aware of memory overhead Enums often require more than twice as much memory as static constants. You should strictly avoid using enums on

Android. Every class in Java (including anonymous inner classes) uses about 500 bytes of code. Every class instance has 12-16 bytes of RAM overhead. Putting a single entry into a HashMap requires the allocation of an additional entry object that takes 32 bytes.

Be careful with code abstractions Often, developers use abstractions simply as a "good programming practice," because abstractions can improve code

flexibility and maintenance. However, abstractions come at a significant cost: generally they require a fair amount more code that needs to be executed, requiring more time and more RAM for that code to be mapped into memory. So if your abstractions aren't supplying a significant benefit, you should avoid them.

CONFIDENTIAL / February 2014 / CEE - CC India

RESTRICTED MORPHO

MORPHO RESTRICTED

22 /

This document and the information therein are the property of Morpho, They must not be copied or communicated to a third party without the prior written authorization of Morpho.

TIPS, CONTINUED…

Avoid dependency injection frameworks Using a dependency injection framework such as Guice or RoboGuice may be attractive because they can simplify

the code you write and provide an adaptive environment that's useful for testing and other configuration changes. However, these frameworks tend to perform a lot of process initialization by scanning your code for annotations, which can require significant amounts of your code to be mapped into RAM even though you don't need it. These mapped pages are allocated into clean memory so Android can drop them, but that won't happen until the pages have been left in memory for a long period of time.

Be careful about using external libraries External library code is often not written for mobile environments and can be inefficient when used for work

on a mobile client. At the very least, when you decide to use an external library, you should assume you are taking on a significant porting and maintenance burden to optimize the library for mobile. Plan for that work up-front and analyze the library in terms of code size and RAM footprint before deciding to use it at all.

Use ProGuard to strip out any unneeded code The ProGuard tool shrinks, optimizes, and obfuscates your code by removing unused code and renaming

classes, fields, and methods with semantically obscure names. Using ProGuard can make your code more compact, requiring fewer RAM pages to be mapped.

Use multiple processes If it's appropriate for your app, an advanced technique that may help you manage your app's memory is

dividing components of your app into multiple processes. This technique must always be used carefully and most apps should not run multiple processes, as it can easily increase—rather than decrease—your RAM footprint if done incorrectly

CONFIDENTIAL / February 2014 / CEE - CC India

RESTRICTED MORPHO

MORPHO RESTRICTED

23 /

This document and the information therein are the property of Morpho, They must not be copied or communicated to a third party without the prior written authorization of Morpho.

TIPS, CONTINUED…

An example of when multiple processes may be appropriate is when building a music player that plays music from a service for long period of time. If the entire app runs in one process, then many of the allocations performed for its activity UI must be kept around as long as it is playing music, even if the user is currently in another app and the service is controlling the playback. An app like this may be split into two process: one for its UI, and the other for the work that continues running in the background service.

You can specify a separate process for each app component by declaring the android:process attribute for each component in the manifest file. For example, you can specify that your service should run in a process separate from your app's main process by declaring a new process named "background" (but you can name the process anything you like):

<service android:name=".PlaybackService"         android:process=":background" />

CONFIDENTIAL / February 2014 / CEE - CC India

RESTRICTED MORPHO

MORPHO RESTRICTEDThis document and the information therein are the property of Morpho, They must not be copied or communicated to a third party without the prior written authorization of Morpho.

• https://developer.android.com/training/articles/memory.html• https://www.google.co.in/

References

RESTRICTED MORPHO

MORPHO RESTRICTEDThis document and the information therein are the property of Morpho, They must not be copied or communicated to a third party without the prior written authorization of Morpho.

Next session Improving Layout Performance

Thank you