SlideShare une entreprise Scribd logo
1  sur  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
RESTRICTED MORPHO
MORPHO RESTRICTED
1 /
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 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.
/01/
Sharing Memory
RESTRICTED MORPHO
MORPHO RESTRICTED
3 /
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 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.
/02/
Allocating and Reclaiming App
Memory
RESTRICTED MORPHO
MORPHO RESTRICTED
5 /
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 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.
/03/
Restricting App Memory
RESTRICTED MORPHO
MORPHO RESTRICTED
7 /
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 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.
/04/
Switching Apps
RESTRICTED MORPHO
MORPHO RESTRICTED
9 /
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 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.
/05/
How Your App Should Manage
Memory
RESTRICTED MORPHO
MORPHO RESTRICTED
11 /
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 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.
/05/01
Use services sparingly
RESTRICTED MORPHO
MORPHO RESTRICTED
13 /
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 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.
/05/02
Release memory when your user
interface becomes hidden
RESTRICTED MORPHO
MORPHO RESTRICTED
15 /
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 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.
/05/03
Release memory as memory
becomes tight
RESTRICTED MORPHO
MORPHO RESTRICTED
17 /
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 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.
/05/04
Check how much memory you
should use
RESTRICTED MORPHO
MORPHO RESTRICTED
19 /
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
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.
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
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, 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
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…
 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 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.
• https://developer.android.com/training/articles/memory.html
• https://www.google.co.in/
References
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.
Next session
Improving Layout Performance
Thank you

Contenu connexe

En vedette

Improved Teaching Leaning Based Optimization Algorithm
Improved Teaching Leaning Based Optimization AlgorithmImproved Teaching Leaning Based Optimization Algorithm
Improved Teaching Leaning Based Optimization Algorithmrajani51
 
BKK16-302: Android Optimizing Compiler: New Member Assimilation Guide
BKK16-302: Android Optimizing Compiler: New Member Assimilation GuideBKK16-302: Android Optimizing Compiler: New Member Assimilation Guide
BKK16-302: Android Optimizing Compiler: New Member Assimilation GuideLinaro
 
Code Optimization
Code OptimizationCode Optimization
Code OptimizationESUG
 
JVM JIT compilation overview by Vladimir Ivanov
JVM JIT compilation overview by Vladimir IvanovJVM JIT compilation overview by Vladimir Ivanov
JVM JIT compilation overview by Vladimir IvanovZeroTurnaround
 
Understanding the Dalvik bytecode with the Dedexer tool
Understanding the Dalvik bytecode with the Dedexer toolUnderstanding the Dalvik bytecode with the Dedexer tool
Understanding the Dalvik bytecode with the Dedexer toolGabor Paller
 
LAS16-201: ART JIT in Android N
LAS16-201: ART JIT in Android NLAS16-201: ART JIT in Android N
LAS16-201: ART JIT in Android NLinaro
 
optimizing code in compilers using parallel genetic algorithm
optimizing code in compilers using parallel genetic algorithm optimizing code in compilers using parallel genetic algorithm
optimizing code in compilers using parallel genetic algorithm Fatemeh Karimi
 
JEEConf 2016. Effectiveness and code optimization in Java applications
JEEConf 2016. Effectiveness and code optimization in  Java applicationsJEEConf 2016. Effectiveness and code optimization in  Java applications
JEEConf 2016. Effectiveness and code optimization in Java applicationsStrannik_2013
 
Google ART (Android RunTime)
Google ART (Android RunTime)Google ART (Android RunTime)
Google ART (Android RunTime)Niraj Solanke
 
IoT Smart Home & Connected Car Convergence Insights from Patents
IoT Smart Home & Connected Car Convergence Insights from PatentsIoT Smart Home & Connected Car Convergence Insights from Patents
IoT Smart Home & Connected Car Convergence Insights from PatentsAlex G. Lee, Ph.D. Esq. CLP
 

En vedette (12)

Abdelrahman Al-Ogail Resume
Abdelrahman Al-Ogail ResumeAbdelrahman Al-Ogail Resume
Abdelrahman Al-Ogail Resume
 
Improved Teaching Leaning Based Optimization Algorithm
Improved Teaching Leaning Based Optimization AlgorithmImproved Teaching Leaning Based Optimization Algorithm
Improved Teaching Leaning Based Optimization Algorithm
 
BKK16-302: Android Optimizing Compiler: New Member Assimilation Guide
BKK16-302: Android Optimizing Compiler: New Member Assimilation GuideBKK16-302: Android Optimizing Compiler: New Member Assimilation Guide
BKK16-302: Android Optimizing Compiler: New Member Assimilation Guide
 
Code Optimization
Code OptimizationCode Optimization
Code Optimization
 
Gc in android
Gc in androidGc in android
Gc in android
 
JVM JIT compilation overview by Vladimir Ivanov
JVM JIT compilation overview by Vladimir IvanovJVM JIT compilation overview by Vladimir Ivanov
JVM JIT compilation overview by Vladimir Ivanov
 
Understanding the Dalvik bytecode with the Dedexer tool
Understanding the Dalvik bytecode with the Dedexer toolUnderstanding the Dalvik bytecode with the Dedexer tool
Understanding the Dalvik bytecode with the Dedexer tool
 
LAS16-201: ART JIT in Android N
LAS16-201: ART JIT in Android NLAS16-201: ART JIT in Android N
LAS16-201: ART JIT in Android N
 
optimizing code in compilers using parallel genetic algorithm
optimizing code in compilers using parallel genetic algorithm optimizing code in compilers using parallel genetic algorithm
optimizing code in compilers using parallel genetic algorithm
 
JEEConf 2016. Effectiveness and code optimization in Java applications
JEEConf 2016. Effectiveness and code optimization in  Java applicationsJEEConf 2016. Effectiveness and code optimization in  Java applications
JEEConf 2016. Effectiveness and code optimization in Java applications
 
Google ART (Android RunTime)
Google ART (Android RunTime)Google ART (Android RunTime)
Google ART (Android RunTime)
 
IoT Smart Home & Connected Car Convergence Insights from Patents
IoT Smart Home & Connected Car Convergence Insights from PatentsIoT Smart Home & Connected Car Convergence Insights from Patents
IoT Smart Home & Connected Car Convergence Insights from Patents
 

Similaire à Android Code Optimization Techniques 2

Android Performance Best Practices
Android Performance Best Practices Android Performance Best Practices
Android Performance Best Practices Amgad Muhammad
 
Performance optimization for Android
Performance optimization for AndroidPerformance optimization for Android
Performance optimization for AndroidArslan Anwar
 
Flutter vs xamarin vs react native - Mobile App Development Framework
Flutter vs xamarin vs react native - Mobile App Development FrameworkFlutter vs xamarin vs react native - Mobile App Development Framework
Flutter vs xamarin vs react native - Mobile App Development Frameworkdeveloperonrents
 
How to do Memory Optimizations in Android
How to do Memory Optimizations in AndroidHow to do Memory Optimizations in Android
How to do Memory Optimizations in AndroidSingsys Pte Ltd
 
Decide if PhoneGap is for you as your mobile platform selection
Decide if PhoneGap is for you as your mobile platform selectionDecide if PhoneGap is for you as your mobile platform selection
Decide if PhoneGap is for you as your mobile platform selectionSalim M Bhonhariya
 
Virtual memory presentation
Virtual memory presentationVirtual memory presentation
Virtual memory presentationRanjeet Kumar
 
ACADGILD:: ANDROID LESSON-How to analyze &amp; manage memory on android like ...
ACADGILD:: ANDROID LESSON-How to analyze &amp; manage memory on android like ...ACADGILD:: ANDROID LESSON-How to analyze &amp; manage memory on android like ...
ACADGILD:: ANDROID LESSON-How to analyze &amp; manage memory on android like ...Padma shree. T
 
Mobile performance testing
Mobile performance testingMobile performance testing
Mobile performance testinghunz
 
Ultimate golang performance optimization guide
Ultimate golang performance optimization guide Ultimate golang performance optimization guide
Ultimate golang performance optimization guide Katy Slemon
 
How To Make Your App Available Offline.pdf
How To Make Your App Available Offline.pdfHow To Make Your App Available Offline.pdf
How To Make Your App Available Offline.pdfSatawaretechnologies1
 
Mobile application security
Mobile application securityMobile application security
Mobile application securityShubhneet Goel
 
Mobile Application Security
Mobile Application SecurityMobile Application Security
Mobile Application SecurityIshan Girdhar
 
Virtual Memory
Virtual MemoryVirtual Memory
Virtual MemoryArchith777
 
Frontend Monoliths: Run if you can!
Frontend Monoliths: Run if you can!Frontend Monoliths: Run if you can!
Frontend Monoliths: Run if you can!Jonas Bandi
 
Flutter App Performance Optimization_ Tips and Techniques.pdf
Flutter App Performance Optimization_ Tips and Techniques.pdfFlutter App Performance Optimization_ Tips and Techniques.pdf
Flutter App Performance Optimization_ Tips and Techniques.pdfDianApps Technologies
 
Interactive Applications in .NET
Interactive Applications in .NETInteractive Applications in .NET
Interactive Applications in .NETAndrei Fangli
 
virtual memory.ppt
virtual memory.pptvirtual memory.ppt
virtual memory.pptsuryansh85
 
HMR Log Analyzer: Analyze Web Application Logs Over Hadoop MapReduce
HMR Log Analyzer: Analyze Web Application Logs Over Hadoop MapReduce HMR Log Analyzer: Analyze Web Application Logs Over Hadoop MapReduce
HMR Log Analyzer: Analyze Web Application Logs Over Hadoop MapReduce ijujournal
 

Similaire à Android Code Optimization Techniques 2 (20)

Android Performance Best Practices
Android Performance Best Practices Android Performance Best Practices
Android Performance Best Practices
 
Android Memory Management
Android Memory ManagementAndroid Memory Management
Android Memory Management
 
Performance optimization for Android
Performance optimization for AndroidPerformance optimization for Android
Performance optimization for Android
 
Flutter vs xamarin vs react native - Mobile App Development Framework
Flutter vs xamarin vs react native - Mobile App Development FrameworkFlutter vs xamarin vs react native - Mobile App Development Framework
Flutter vs xamarin vs react native - Mobile App Development Framework
 
How to do Memory Optimizations in Android
How to do Memory Optimizations in AndroidHow to do Memory Optimizations in Android
How to do Memory Optimizations in Android
 
Decide if PhoneGap is for you as your mobile platform selection
Decide if PhoneGap is for you as your mobile platform selectionDecide if PhoneGap is for you as your mobile platform selection
Decide if PhoneGap is for you as your mobile platform selection
 
Virtual memory presentation
Virtual memory presentationVirtual memory presentation
Virtual memory presentation
 
ACADGILD:: ANDROID LESSON-How to analyze &amp; manage memory on android like ...
ACADGILD:: ANDROID LESSON-How to analyze &amp; manage memory on android like ...ACADGILD:: ANDROID LESSON-How to analyze &amp; manage memory on android like ...
ACADGILD:: ANDROID LESSON-How to analyze &amp; manage memory on android like ...
 
Mobile performance testing
Mobile performance testingMobile performance testing
Mobile performance testing
 
Ultimate golang performance optimization guide
Ultimate golang performance optimization guide Ultimate golang performance optimization guide
Ultimate golang performance optimization guide
 
How To Make Your App Available Offline.pdf
How To Make Your App Available Offline.pdfHow To Make Your App Available Offline.pdf
How To Make Your App Available Offline.pdf
 
Mobile application security
Mobile application securityMobile application security
Mobile application security
 
Mobile Application Security
Mobile Application SecurityMobile Application Security
Mobile Application Security
 
Virtual Memory
Virtual MemoryVirtual Memory
Virtual Memory
 
Frontend Monoliths: Run if you can!
Frontend Monoliths: Run if you can!Frontend Monoliths: Run if you can!
Frontend Monoliths: Run if you can!
 
Flutter App Performance Optimization_ Tips and Techniques.pdf
Flutter App Performance Optimization_ Tips and Techniques.pdfFlutter App Performance Optimization_ Tips and Techniques.pdf
Flutter App Performance Optimization_ Tips and Techniques.pdf
 
Interactive Applications in .NET
Interactive Applications in .NETInteractive Applications in .NET
Interactive Applications in .NET
 
virtual memory.ppt
virtual memory.pptvirtual memory.ppt
virtual memory.ppt
 
[IJCT-V3I2P36] Authors: Amarbir Singh
[IJCT-V3I2P36] Authors: Amarbir Singh[IJCT-V3I2P36] Authors: Amarbir Singh
[IJCT-V3I2P36] Authors: Amarbir Singh
 
HMR Log Analyzer: Analyze Web Application Logs Over Hadoop MapReduce
HMR Log Analyzer: Analyze Web Application Logs Over Hadoop MapReduce HMR Log Analyzer: Analyze Web Application Logs Over Hadoop MapReduce
HMR Log Analyzer: Analyze Web Application Logs Over Hadoop MapReduce
 

Dernier

Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfStefano Stabellini
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Developmentvyaparkranti
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxAndreas Kunz
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...Akihiro Suda
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZABSYZ Inc
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf31events.com
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLionel Briand
 

Dernier (20)

2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdf
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Development
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZ
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and Repair
 

Android Code Optimization Techniques 2

  • 1. 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
  • 2. RESTRICTED MORPHO MORPHO RESTRICTED 1 / 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
  • 3. 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. /01/ Sharing Memory
  • 4. RESTRICTED MORPHO MORPHO RESTRICTED 3 / 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.
  • 5. 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. /02/ Allocating and Reclaiming App Memory
  • 6. RESTRICTED MORPHO MORPHO RESTRICTED 5 / 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
  • 7. 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. /03/ Restricting App Memory
  • 8. RESTRICTED MORPHO MORPHO RESTRICTED 7 / 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
  • 9. 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. /04/ Switching Apps
  • 10. RESTRICTED MORPHO MORPHO RESTRICTED 9 / 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
  • 11. 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. /05/ How Your App Should Manage Memory
  • 12. RESTRICTED MORPHO MORPHO RESTRICTED 11 / 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
  • 13. 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. /05/01 Use services sparingly
  • 14. RESTRICTED MORPHO MORPHO RESTRICTED 13 / 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
  • 15. 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. /05/02 Release memory when your user interface becomes hidden
  • 16. RESTRICTED MORPHO MORPHO RESTRICTED 15 / 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
  • 17. 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. /05/03 Release memory as memory becomes tight
  • 18. RESTRICTED MORPHO MORPHO RESTRICTED 17 / 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
  • 19. 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. /05/04 Check how much memory you should use
  • 20. RESTRICTED MORPHO MORPHO RESTRICTED 19 / 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
  • 21. 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. 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
  • 22. 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, 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
  • 23. 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…  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
  • 24. 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. • https://developer.android.com/training/articles/memory.html • https://www.google.co.in/ References
  • 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. Next session Improving Layout Performance Thank you