SlideShare a Scribd company logo
Android Memory Optimization
Best Practices for Better
Memory Management
Two types of memories in Android
Clean RAM
Android makes memory available to the system through paging and memory-
mapping techniques which is clean RAM. Files and resources are kept in
mapped pages which can be easily recovered from disk hence these can be
paged out and memory can be released for the system.
Dirty RAM
Dirty RAM is one that is quite expensive when runs in background since they
cannot be paged out. Maximum memory inside a running application is dirty
memory and it is used for memory optimization.
Android Memory Overview
All applications are recognized by android either as running process or
cached process. Android kills one or multiple cached processes when
there is need of memory for running process. According to LRU (least
recently used) process under cached process are killed.
Memory Optimization: Best practices for
enhanced memory usage
When the system is not running out of memory then it is good for
boosting the overall memory usage and performance of Android and
eventually ensure a delightful user experience.
Avoid Memory Leaks at all cost
✓ Main reason for memory leak is to forget to free up the allocated memory
before all related references go out of the scope. Memory leaks happen
when references to the objects that are no longer needed in an app are
not released and this type of memory leaks are known as logical memory
leaks.
✓ A very strong Logical memory leaks is the result of not releasing references
to those objects that are no more required in app. When a strong
reference to an object is still present then even the garbage collector fails
to remove the object from the memory
Avoid Memory Leaks at all cost
Avoid Memory Leaks at all cost
It can be avoided by following ways:
✓ Once the database query is done always close the cursor.
✓ Remember to call unregisterReceiver() after calling
registerReceiver().
✓ Significant memory loss is caused by Activity instance leakage and
it also increases the OOM(out of memory) value.
This can be avoided as following:
✓ Don’t keep the long-lived references to a context-activity.
✓ Replace the context-activity with context-application.
✓ Use AsyncTask for short-lived operations.
Profile guided Dex file layout
Profile guided Dex file layout
Application is wrapped in an APK file where multiple dex files
(contains instruction for application execution) are present and when
an application is launched on the device, the dex file is read by device
into memory with several hundred pages being loaded into the
memory. Usually, developers are not aware about important use
cases required by a specific user hence, there are all a lot of
unimportant things present along with important things.
Profile guided Dex file layout
To improve the Dex file layout use the JIT profile information for moving important things
close to each other as shown below:
Profile guided Dex file layout
Below snapshot showcase a significant reduction in RAM usage by dex file after
layout.
Code Sinking
In this type of optimization instructions are moved closer to those instructions
that actually use them. Instructions that are rarely used need to be moved
closer to where they are used. It basically means instruction not in the regular
flow should be moved to the exceptional cases.
Code Sinking
It is a common optimization technique in object oriented language a runtime
will try to infer classes and methods that can be made final even though they
aren't final actually. Having this information internally gives a lot of room for
the compiler for more optimizations.
Class Hierarchy Analysis
Class Hierarchy Analysis
Loop Optimization
Programs tend to spend most of the time inside loops. Loop optimization has an analysis part
where we look into the program and transformations are performed in the optimization part.
Optimized Data Containers
Few classes provided are not optimized for usage on mobile devices.
Implementation of generic HashMap is a bit memory intensive due to its
requirement for a separate entry object in each mapping. This memory issue
can be solved by using optimized data containers like SparseArray,
SparseBooleanArray, and LongSparseArray. As SparseArray classes avoid the
system requirement to autobox the key and sometimes the value thus, they are
more efficient. When required switch to raw arrays for lean data structure.
Choose Data Types Wisely
Using primitive types will reduce the memory usage. An integer objects
consume 4 times more memory than a primitive int. Similarly, a boolean object
will occupy more memory than a primitive boolean type. For Constants prefer
static final variables as they consume half the memory in comparison to enums.
How to do Memory Optimizations in Android

More Related Content

What's hot

What's hot (6)

Amazon OpenSearch Service
Amazon OpenSearch ServiceAmazon OpenSearch Service
Amazon OpenSearch Service
 
Driver Drowsiness / Fatigue Detection Solution
Driver Drowsiness / Fatigue Detection SolutionDriver Drowsiness / Fatigue Detection Solution
Driver Drowsiness / Fatigue Detection Solution
 
Androd rest client architecture
Androd rest client architectureAndrod rest client architecture
Androd rest client architecture
 
Making awesome apps
Making awesome appsMaking awesome apps
Making awesome apps
 
Driver Drowsiness Detection Using Matlab
Driver Drowsiness Detection Using MatlabDriver Drowsiness Detection Using Matlab
Driver Drowsiness Detection Using Matlab
 
Lightning page optimization & best practices
Lightning page optimization & best practicesLightning page optimization & best practices
Lightning page optimization & best practices
 

Similar to How to do Memory Optimizations in Android

Chapter 2 part 1
Chapter 2 part 1Chapter 2 part 1
Chapter 2 part 1
rohassanie
 
Android Performance Best Practices
Android Performance Best Practices Android Performance Best Practices
Android Performance Best Practices
Amgad Muhammad
 
scale_perf_best_practices
scale_perf_best_practicesscale_perf_best_practices
scale_perf_best_practices
webuploader
 
Optimisation and performance in Android
Optimisation and performance in AndroidOptimisation and performance in Android
Optimisation and performance in Android
Rakesh Jha
 
Memory Management in Go: Stack, Heap & Garbage Collector
Memory Management in Go: Stack, Heap & Garbage CollectorMemory Management in Go: Stack, Heap & Garbage Collector
Memory Management in Go: Stack, Heap & Garbage Collector
Wednesday Solutions
 
Virtual Memory vs Cache Memory
Virtual Memory vs Cache MemoryVirtual Memory vs Cache Memory
Virtual Memory vs Cache Memory
Ashik Iqbal
 

Similar to How to do Memory Optimizations in Android (20)

Android Memory Management
Android Memory ManagementAndroid Memory Management
Android Memory Management
 
Chapter 2 part 1
Chapter 2 part 1Chapter 2 part 1
Chapter 2 part 1
 
ACADGILD:: ANDROID LESSON-How to analyze & manage memory on android like ...
ACADGILD:: ANDROID LESSON-How to analyze & manage memory on android like ...ACADGILD:: ANDROID LESSON-How to analyze & manage memory on android like ...
ACADGILD:: ANDROID LESSON-How to analyze & manage memory on android like ...
 
Paging +Algorithem+Segmentation+memory management
Paging +Algorithem+Segmentation+memory managementPaging +Algorithem+Segmentation+memory management
Paging +Algorithem+Segmentation+memory management
 
Low memory footprint programs-iSeries
Low memory footprint programs-iSeriesLow memory footprint programs-iSeries
Low memory footprint programs-iSeries
 
Performance optimization for Android
Performance optimization for AndroidPerformance optimization for Android
Performance optimization for Android
 
Android Performance Best Practices
Android Performance Best Practices Android Performance Best Practices
Android Performance Best Practices
 
scale_perf_best_practices
scale_perf_best_practicesscale_perf_best_practices
scale_perf_best_practices
 
Optimisation and performance in Android
Optimisation and performance in AndroidOptimisation and performance in Android
Optimisation and performance in Android
 
Memory Hierarchy
Memory HierarchyMemory Hierarchy
Memory Hierarchy
 
Abhaycavirtual memory and the pagehit.pptx
Abhaycavirtual memory and the pagehit.pptxAbhaycavirtual memory and the pagehit.pptx
Abhaycavirtual memory and the pagehit.pptx
 
Os unit 2
Os unit 2Os unit 2
Os unit 2
 
Memory Management in Go: Stack, Heap & Garbage Collector
Memory Management in Go: Stack, Heap & Garbage CollectorMemory Management in Go: Stack, Heap & Garbage Collector
Memory Management in Go: Stack, Heap & Garbage Collector
 
Operating system Memory management
Operating system Memory management Operating system Memory management
Operating system Memory management
 
virtual memory.ppt
virtual memory.pptvirtual memory.ppt
virtual memory.ppt
 
Virtual Memory vs Cache Memory
Virtual Memory vs Cache MemoryVirtual Memory vs Cache Memory
Virtual Memory vs Cache Memory
 
Paging-R.D.Sivakumar
Paging-R.D.SivakumarPaging-R.D.Sivakumar
Paging-R.D.Sivakumar
 
Paging-R.D.Sivakumar
Paging-R.D.SivakumarPaging-R.D.Sivakumar
Paging-R.D.Sivakumar
 
CSI-503 - 6. Memory Management
CSI-503 - 6. Memory Management CSI-503 - 6. Memory Management
CSI-503 - 6. Memory Management
 
NOV11 virtual memory.ppt
NOV11 virtual memory.pptNOV11 virtual memory.ppt
NOV11 virtual memory.ppt
 

More from Singsys Pte Ltd

More from Singsys Pte Ltd (18)

Technical Seminar Series: GIT Pull Requests Best Practices
Technical Seminar Series:  GIT Pull Requests Best PracticesTechnical Seminar Series:  GIT Pull Requests Best Practices
Technical Seminar Series: GIT Pull Requests Best Practices
 
Laravel Security Standards
Laravel Security Standards Laravel Security Standards
Laravel Security Standards
 
Android OS - The Journey of most popular Operating System
Android OS - The Journey of most popular Operating SystemAndroid OS - The Journey of most popular Operating System
Android OS - The Journey of most popular Operating System
 
How to Create WordPress Website in Easy Steps
How to Create WordPress Website in Easy StepsHow to Create WordPress Website in Easy Steps
How to Create WordPress Website in Easy Steps
 
Basics of-linux
Basics of-linuxBasics of-linux
Basics of-linux
 
SoLoMo
SoLoMoSoLoMo
SoLoMo
 
Introduction to facebook sdk
Introduction to facebook sdkIntroduction to facebook sdk
Introduction to facebook sdk
 
Html5 tutorial for beginners
Html5 tutorial for beginnersHtml5 tutorial for beginners
Html5 tutorial for beginners
 
Beginners css tutorial for web designers
Beginners css tutorial for web designersBeginners css tutorial for web designers
Beginners css tutorial for web designers
 
Joomla 3 installation and management guide
Joomla 3 installation and management guideJoomla 3 installation and management guide
Joomla 3 installation and management guide
 
Joomla Introduction & Installation Tutorial
Joomla Introduction & Installation TutorialJoomla Introduction & Installation Tutorial
Joomla Introduction & Installation Tutorial
 
Basic of web design
Basic of web designBasic of web design
Basic of web design
 
Embedded Technology
Embedded TechnologyEmbedded Technology
Embedded Technology
 
Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
 
Technical seo tips for web developers
Technical seo tips for web developersTechnical seo tips for web developers
Technical seo tips for web developers
 
WordPress Website Design and Development
WordPress Website Design and DevelopmentWordPress Website Design and Development
WordPress Website Design and Development
 
Being a designer
Being a designerBeing a designer
Being a designer
 
Points for Design and Development of SEO friendly websites
Points for Design and Development of SEO friendly websitesPoints for Design and Development of SEO friendly websites
Points for Design and Development of SEO friendly websites
 

Recently uploaded

Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
Bhaskar Mitra
 

Recently uploaded (20)

Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
 
Speed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in MinutesSpeed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in Minutes
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
Free and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi IbrahimzadeFree and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
 
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
 
AI revolution and Salesforce, Jiří Karpíšek
AI revolution and Salesforce, Jiří KarpíšekAI revolution and Salesforce, Jiří Karpíšek
AI revolution and Salesforce, Jiří Karpíšek
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
What's New in Teams Calling, Meetings and Devices April 2024
What's New in Teams Calling, Meetings and Devices April 2024What's New in Teams Calling, Meetings and Devices April 2024
What's New in Teams Calling, Meetings and Devices April 2024
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
Salesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
Salesforce Adoption – Metrics, Methods, and Motivation, Antone KomSalesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
Salesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
 
10 Differences between Sales Cloud and CPQ, Blanka Doktorová
10 Differences between Sales Cloud and CPQ, Blanka Doktorová10 Differences between Sales Cloud and CPQ, Blanka Doktorová
10 Differences between Sales Cloud and CPQ, Blanka Doktorová
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
 
Demystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John StaveleyDemystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John Staveley
 
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
 
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
 

How to do Memory Optimizations in Android

  • 1. Android Memory Optimization Best Practices for Better Memory Management
  • 2. Two types of memories in Android Clean RAM Android makes memory available to the system through paging and memory- mapping techniques which is clean RAM. Files and resources are kept in mapped pages which can be easily recovered from disk hence these can be paged out and memory can be released for the system. Dirty RAM Dirty RAM is one that is quite expensive when runs in background since they cannot be paged out. Maximum memory inside a running application is dirty memory and it is used for memory optimization.
  • 3. Android Memory Overview All applications are recognized by android either as running process or cached process. Android kills one or multiple cached processes when there is need of memory for running process. According to LRU (least recently used) process under cached process are killed.
  • 4. Memory Optimization: Best practices for enhanced memory usage When the system is not running out of memory then it is good for boosting the overall memory usage and performance of Android and eventually ensure a delightful user experience.
  • 5. Avoid Memory Leaks at all cost ✓ Main reason for memory leak is to forget to free up the allocated memory before all related references go out of the scope. Memory leaks happen when references to the objects that are no longer needed in an app are not released and this type of memory leaks are known as logical memory leaks. ✓ A very strong Logical memory leaks is the result of not releasing references to those objects that are no more required in app. When a strong reference to an object is still present then even the garbage collector fails to remove the object from the memory
  • 6. Avoid Memory Leaks at all cost
  • 7. Avoid Memory Leaks at all cost It can be avoided by following ways: ✓ Once the database query is done always close the cursor. ✓ Remember to call unregisterReceiver() after calling registerReceiver(). ✓ Significant memory loss is caused by Activity instance leakage and it also increases the OOM(out of memory) value. This can be avoided as following: ✓ Don’t keep the long-lived references to a context-activity. ✓ Replace the context-activity with context-application. ✓ Use AsyncTask for short-lived operations.
  • 8. Profile guided Dex file layout
  • 9. Profile guided Dex file layout Application is wrapped in an APK file where multiple dex files (contains instruction for application execution) are present and when an application is launched on the device, the dex file is read by device into memory with several hundred pages being loaded into the memory. Usually, developers are not aware about important use cases required by a specific user hence, there are all a lot of unimportant things present along with important things.
  • 10. Profile guided Dex file layout To improve the Dex file layout use the JIT profile information for moving important things close to each other as shown below:
  • 11. Profile guided Dex file layout Below snapshot showcase a significant reduction in RAM usage by dex file after layout.
  • 12. Code Sinking In this type of optimization instructions are moved closer to those instructions that actually use them. Instructions that are rarely used need to be moved closer to where they are used. It basically means instruction not in the regular flow should be moved to the exceptional cases.
  • 14. It is a common optimization technique in object oriented language a runtime will try to infer classes and methods that can be made final even though they aren't final actually. Having this information internally gives a lot of room for the compiler for more optimizations. Class Hierarchy Analysis
  • 16. Loop Optimization Programs tend to spend most of the time inside loops. Loop optimization has an analysis part where we look into the program and transformations are performed in the optimization part.
  • 17. Optimized Data Containers Few classes provided are not optimized for usage on mobile devices. Implementation of generic HashMap is a bit memory intensive due to its requirement for a separate entry object in each mapping. This memory issue can be solved by using optimized data containers like SparseArray, SparseBooleanArray, and LongSparseArray. As SparseArray classes avoid the system requirement to autobox the key and sometimes the value thus, they are more efficient. When required switch to raw arrays for lean data structure.
  • 18. Choose Data Types Wisely Using primitive types will reduce the memory usage. An integer objects consume 4 times more memory than a primitive int. Similarly, a boolean object will occupy more memory than a primitive boolean type. For Constants prefer static final variables as they consume half the memory in comparison to enums.