SlideShare a Scribd company logo
1 of 19
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

TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Recently uploaded (20)

AI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by Anitaraj
 
Navigating Identity and Access Management in the Modern Enterprise
Navigating Identity and Access Management in the Modern EnterpriseNavigating Identity and Access Management in the Modern Enterprise
Navigating Identity and Access Management in the Modern Enterprise
 
Less Is More: Utilizing Ballerina to Architect a Cloud Data Platform
Less Is More: Utilizing Ballerina to Architect a Cloud Data PlatformLess Is More: Utilizing Ballerina to Architect a Cloud Data Platform
Less Is More: Utilizing Ballerina to Architect a Cloud Data Platform
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Choreo: Empowering the Future of Enterprise Software Engineering
Choreo: Empowering the Future of Enterprise Software EngineeringChoreo: Empowering the Future of Enterprise Software Engineering
Choreo: Empowering the Future of Enterprise Software Engineering
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....
TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....
TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Simplifying Mobile A11y Presentation.pptx
Simplifying Mobile A11y Presentation.pptxSimplifying Mobile A11y Presentation.pptx
Simplifying Mobile A11y Presentation.pptx
 
Modernizing Legacy Systems Using Ballerina
Modernizing Legacy Systems Using BallerinaModernizing Legacy Systems Using Ballerina
Modernizing Legacy Systems Using Ballerina
 
Quantum Leap in Next-Generation Computing
Quantum Leap in Next-Generation ComputingQuantum Leap in Next-Generation Computing
Quantum Leap in Next-Generation Computing
 

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.