SlideShare a Scribd company logo
1 of 25
Download to read offline
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

More Related Content

Viewers also liked

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
 

Viewers also liked (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
 

Similar to 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
 
Memory Leak in Flutter Apps.pdf
Memory Leak in Flutter Apps.pdfMemory Leak in Flutter Apps.pdf
Memory Leak in Flutter Apps.pdfFlutter Agency
 
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
 

Similar to 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
 
Memory Leak in Flutter Apps.pdf
Memory Leak in Flutter Apps.pdfMemory Leak in Flutter Apps.pdf
Memory Leak in Flutter Apps.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
 

Recently uploaded

Leveraging DxSherpa's Generative AI Services to Unlock Human-Machine Harmony
Leveraging DxSherpa's Generative AI Services to Unlock Human-Machine HarmonyLeveraging DxSherpa's Generative AI Services to Unlock Human-Machine Harmony
Leveraging DxSherpa's Generative AI Services to Unlock Human-Machine Harmonyelliciumsolutionspun
 
online pdf editor software solutions.pdf
online pdf editor software solutions.pdfonline pdf editor software solutions.pdf
online pdf editor software solutions.pdfMeon Technology
 
eAuditor Audits & Inspections - conduct field inspections
eAuditor Audits & Inspections - conduct field inspectionseAuditor Audits & Inspections - conduct field inspections
eAuditor Audits & Inspections - conduct field inspectionsNirav Modi
 
Cybersecurity Challenges with Generative AI - for Good and Bad
Cybersecurity Challenges with Generative AI - for Good and BadCybersecurity Challenges with Generative AI - for Good and Bad
Cybersecurity Challenges with Generative AI - for Good and BadIvo Andreev
 
Mastering Kubernetes - Basics and Advanced Concepts using Example Project
Mastering Kubernetes - Basics and Advanced Concepts using Example ProjectMastering Kubernetes - Basics and Advanced Concepts using Example Project
Mastering Kubernetes - Basics and Advanced Concepts using Example Projectwajrcs
 
AI Embracing Every Shade of Human Beauty
AI Embracing Every Shade of Human BeautyAI Embracing Every Shade of Human Beauty
AI Embracing Every Shade of Human BeautyRaymond Okyere-Forson
 
Deep Learning for Images with PyTorch - Datacamp
Deep Learning for Images with PyTorch - DatacampDeep Learning for Images with PyTorch - Datacamp
Deep Learning for Images with PyTorch - DatacampVICTOR MAESTRE RAMIREZ
 
Optimizing Business Potential: A Guide to Outsourcing Engineering Services in...
Optimizing Business Potential: A Guide to Outsourcing Engineering Services in...Optimizing Business Potential: A Guide to Outsourcing Engineering Services in...
Optimizing Business Potential: A Guide to Outsourcing Engineering Services in...Jaydeep Chhasatia
 
Webinar - IA generativa e grafi Neo4j: RAG time!
Webinar - IA generativa e grafi Neo4j: RAG time!Webinar - IA generativa e grafi Neo4j: RAG time!
Webinar - IA generativa e grafi Neo4j: RAG time!Neo4j
 
Big Data Bellevue Meetup | Enhancing Python Data Loading in the Cloud for AI/ML
Big Data Bellevue Meetup | Enhancing Python Data Loading in the Cloud for AI/MLBig Data Bellevue Meetup | Enhancing Python Data Loading in the Cloud for AI/ML
Big Data Bellevue Meetup | Enhancing Python Data Loading in the Cloud for AI/MLAlluxio, Inc.
 
Growing Oxen: channel operators and retries
Growing Oxen: channel operators and retriesGrowing Oxen: channel operators and retries
Growing Oxen: channel operators and retriesSoftwareMill
 
Kubernetes go-live checklist for your microservices.pptx
Kubernetes go-live checklist for your microservices.pptxKubernetes go-live checklist for your microservices.pptx
Kubernetes go-live checklist for your microservices.pptxPrakarsh -
 
Your Vision, Our Expertise: TECUNIQUE's Tailored Software Teams
Your Vision, Our Expertise: TECUNIQUE's Tailored Software TeamsYour Vision, Our Expertise: TECUNIQUE's Tailored Software Teams
Your Vision, Our Expertise: TECUNIQUE's Tailored Software TeamsJaydeep Chhasatia
 
Transforming PMO Success with AI - Discover OnePlan Strategic Portfolio Work ...
Transforming PMO Success with AI - Discover OnePlan Strategic Portfolio Work ...Transforming PMO Success with AI - Discover OnePlan Strategic Portfolio Work ...
Transforming PMO Success with AI - Discover OnePlan Strategic Portfolio Work ...OnePlan Solutions
 
Introduction-to-Software-Development-Outsourcing.pptx
Introduction-to-Software-Development-Outsourcing.pptxIntroduction-to-Software-Development-Outsourcing.pptx
Introduction-to-Software-Development-Outsourcing.pptxIntelliSource Technologies
 
IA Generativa y Grafos de Neo4j: RAG time
IA Generativa y Grafos de Neo4j: RAG timeIA Generativa y Grafos de Neo4j: RAG time
IA Generativa y Grafos de Neo4j: RAG timeNeo4j
 
How Does the Epitome of Spyware Differ from Other Malicious Software?
How Does the Epitome of Spyware Differ from Other Malicious Software?How Does the Epitome of Spyware Differ from Other Malicious Software?
How Does the Epitome of Spyware Differ from Other Malicious Software?AmeliaSmith90
 
Watermarking in Source Code: Applications and Security Challenges
Watermarking in Source Code: Applications and Security ChallengesWatermarking in Source Code: Applications and Security Challenges
Watermarking in Source Code: Applications and Security ChallengesShyamsundar Das
 
Top Software Development Trends in 2024
Top Software Development Trends in  2024Top Software Development Trends in  2024
Top Software Development Trends in 2024Mind IT Systems
 

Recently uploaded (20)

Leveraging DxSherpa's Generative AI Services to Unlock Human-Machine Harmony
Leveraging DxSherpa's Generative AI Services to Unlock Human-Machine HarmonyLeveraging DxSherpa's Generative AI Services to Unlock Human-Machine Harmony
Leveraging DxSherpa's Generative AI Services to Unlock Human-Machine Harmony
 
online pdf editor software solutions.pdf
online pdf editor software solutions.pdfonline pdf editor software solutions.pdf
online pdf editor software solutions.pdf
 
eAuditor Audits & Inspections - conduct field inspections
eAuditor Audits & Inspections - conduct field inspectionseAuditor Audits & Inspections - conduct field inspections
eAuditor Audits & Inspections - conduct field inspections
 
Sustainable Web Design - Claire Thornewill
Sustainable Web Design - Claire ThornewillSustainable Web Design - Claire Thornewill
Sustainable Web Design - Claire Thornewill
 
Cybersecurity Challenges with Generative AI - for Good and Bad
Cybersecurity Challenges with Generative AI - for Good and BadCybersecurity Challenges with Generative AI - for Good and Bad
Cybersecurity Challenges with Generative AI - for Good and Bad
 
Mastering Kubernetes - Basics and Advanced Concepts using Example Project
Mastering Kubernetes - Basics and Advanced Concepts using Example ProjectMastering Kubernetes - Basics and Advanced Concepts using Example Project
Mastering Kubernetes - Basics and Advanced Concepts using Example Project
 
AI Embracing Every Shade of Human Beauty
AI Embracing Every Shade of Human BeautyAI Embracing Every Shade of Human Beauty
AI Embracing Every Shade of Human Beauty
 
Deep Learning for Images with PyTorch - Datacamp
Deep Learning for Images with PyTorch - DatacampDeep Learning for Images with PyTorch - Datacamp
Deep Learning for Images with PyTorch - Datacamp
 
Optimizing Business Potential: A Guide to Outsourcing Engineering Services in...
Optimizing Business Potential: A Guide to Outsourcing Engineering Services in...Optimizing Business Potential: A Guide to Outsourcing Engineering Services in...
Optimizing Business Potential: A Guide to Outsourcing Engineering Services in...
 
Webinar - IA generativa e grafi Neo4j: RAG time!
Webinar - IA generativa e grafi Neo4j: RAG time!Webinar - IA generativa e grafi Neo4j: RAG time!
Webinar - IA generativa e grafi Neo4j: RAG time!
 
Big Data Bellevue Meetup | Enhancing Python Data Loading in the Cloud for AI/ML
Big Data Bellevue Meetup | Enhancing Python Data Loading in the Cloud for AI/MLBig Data Bellevue Meetup | Enhancing Python Data Loading in the Cloud for AI/ML
Big Data Bellevue Meetup | Enhancing Python Data Loading in the Cloud for AI/ML
 
Growing Oxen: channel operators and retries
Growing Oxen: channel operators and retriesGrowing Oxen: channel operators and retries
Growing Oxen: channel operators and retries
 
Kubernetes go-live checklist for your microservices.pptx
Kubernetes go-live checklist for your microservices.pptxKubernetes go-live checklist for your microservices.pptx
Kubernetes go-live checklist for your microservices.pptx
 
Your Vision, Our Expertise: TECUNIQUE's Tailored Software Teams
Your Vision, Our Expertise: TECUNIQUE's Tailored Software TeamsYour Vision, Our Expertise: TECUNIQUE's Tailored Software Teams
Your Vision, Our Expertise: TECUNIQUE's Tailored Software Teams
 
Transforming PMO Success with AI - Discover OnePlan Strategic Portfolio Work ...
Transforming PMO Success with AI - Discover OnePlan Strategic Portfolio Work ...Transforming PMO Success with AI - Discover OnePlan Strategic Portfolio Work ...
Transforming PMO Success with AI - Discover OnePlan Strategic Portfolio Work ...
 
Introduction-to-Software-Development-Outsourcing.pptx
Introduction-to-Software-Development-Outsourcing.pptxIntroduction-to-Software-Development-Outsourcing.pptx
Introduction-to-Software-Development-Outsourcing.pptx
 
IA Generativa y Grafos de Neo4j: RAG time
IA Generativa y Grafos de Neo4j: RAG timeIA Generativa y Grafos de Neo4j: RAG time
IA Generativa y Grafos de Neo4j: RAG time
 
How Does the Epitome of Spyware Differ from Other Malicious Software?
How Does the Epitome of Spyware Differ from Other Malicious Software?How Does the Epitome of Spyware Differ from Other Malicious Software?
How Does the Epitome of Spyware Differ from Other Malicious Software?
 
Watermarking in Source Code: Applications and Security Challenges
Watermarking in Source Code: Applications and Security ChallengesWatermarking in Source Code: Applications and Security Challenges
Watermarking in Source Code: Applications and Security Challenges
 
Top Software Development Trends in 2024
Top Software Development Trends in  2024Top Software Development Trends in  2024
Top Software Development Trends in 2024
 

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