SlideShare a Scribd company logo
1 of 4
Download to read offline
Downloaded from: justpaste.it/85hq5
Android memory and performance optimization
Android memory and performance optimization. This tutorial describes how to optimize the usage of memory and
optimize your performance in your Android application. The tutorial is based on Android Studio,android studio
course
1. Programming tips for providing highly responsive and fast
Android applications
1.1. Why you should be careful with Android resources
Android devices have less power than standard desktop or notebook computers. For this reason you must be
careful with memory consumption.
Especially on Android devices before Android 5.0 you want to avoid triggering the garbage collector of the Java
virtual machine. This results in a freeze of the Android runtime for about 200 ms. This can be a notable delay, if the
user is, for example, scrolling down a list.
1.2. Avoid unnecessary object allocation
Avoid creating unnecessary objects, especially in expensive places. Reuse objects if possible. Creating
unnecessary objects triggers the garbage collection more frequently, and this should be avoided.
For example avoid object creating in loops or in the onDraw() method of your custom view.
1.3. Use efficient data structures
Android provides several implementations of Sparse*Array classes. Consider the following code.
Map<Integer, String> map = new HashMap<Integer, String>();
Using this code results in unnecessary Integer objects created.
Android provides data structures which are more efficient for mapping values to other objects. If possible use these
objects, they avoid object creation as in the case of using HashMap. Object creation can be expensive and should
be avoided to reduce the number of times the garbage collector needs to run.
The table give examples for SparseArrays.
Table 1. Efficient memory structures
Memory structure Description
SparseArray<E> Maps integers to Objects, avoid the creation of Integer objects.
SparseBooleanArray Maps integers to booleans.
SparseIntArray Maps integers to integers
To improve the above example, prefer to use the following data structure.
SparseArray<String> map = new SparseArray<String>(); map.put(1, "Hello");
2. Handling bitmaps
Bitmaps can allocate lots of memory if loaded at full size. It is recommended to load the bitmaps in the desired size
into memory. Assume you have an application which displays an image in 100x100 dp, you should load the image
in exactly this size.
A common way is to first measure the bitmap without loading it via a flag passed to the BitmapFactory.
// instruct BitmapFactory to only the bounds and type of the image
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true; BitmapFactory.decodeResource(getResources(),
R.id.myimage, options); // get width and height int imageHeight = options.outHeight;
int imageWidth = options.outWidth; // type of the image String imageType =
options.outMimeType;
Afterwards you can load the scaled version of the image. Android is really good in scaling images by a power of
two. You can use the following method (from the official Android documentation) to calculate the scale factor on a
basis of 2.
public static Bitmap decodeBitmapWithGiveSizeFromResource(Resources res, int resId,
int reqWidth, int reqHeight) { // First decode with inJustDecodeBounds=true to check
dimensions final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true; BitmapFactory.decodeResource(res, resId,
options); // Calculate inSampleSize options.inSampleSize =
calculateInSampleSize(options, reqWidth, reqHeight); // Decode bitmap with
inSampleSize set options.inJustDecodeBounds = false; return
BitmapFactory.decodeResource(res, resId, options); } public static int
calculateInSampleSize( BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image final int height = options.outHeight; final int
width = options.outWidth; int inSampleSize = 1; if (height > reqHeight || width >
reqWidth) { final int halfHeight = height / 2; final int halfWidth = width / 2; //
Calculate the largest inSampleSize value that is a power of 2 and keeps both //
height and width larger than the requested height and width. while ((halfHeight /
inSampleSize) > reqHeight && (halfWidth / inSampleSize) > reqWidth) { inSampleSize
*= 2; } } return inSampleSize; }
This method can be used to assign the image to a view as demonstrated in the following example.
viewWidth = imageView.getWidth(); viewHeight = imageView.getHeight(); imageView.
imageView.setImageBitmap( decodeSampledBitmapFromResource(getResources(),
R.id.myimage, viewWidth, viewHeight));
3. Using caches
3.1. Using a cache
A cache allows reusing objects which are expensive to create. If you load on object into memory, you can think of
this as a cache for the object. For example, if you downloading images from the Internet to display them in a list
you should hold them in memory to avoid that you download them several times.
At some point you need to recycle some of your objects, otherwise you run out of memory. A good approach to do
this, is to recycle the objects which have not been used the longest in your application.
The Android platform provides the LruCache class, as of API 12 (or in the support-v4 library).
The LruCache class provides a _least recently used cache _ (LRU cache) cache implementation. A LRU cache
keeps track of the usage of its members. It has a given size and if this size is exceeded, it removes the items which
have not be accessed the longest. This behavior is depicted in the following graphic.
The following example code demonstrates a possible implementation of the LruCache class for caching images.
public class ImageCache extends LruCache<String, Bitmap> { public ImageCache( int
maxSize ) { super( maxSize ); } @Override protected int sizeOf( String key, Bitmap
value ) { return value.getByteCount(); } @Override protected void entryRemoved(
boolean evicted, String key, Bitmap oldValue, Bitmap newValue ) {
oldValue.recycle(); } }
Its usage is simple and demonstrated by the following example code.
LruCache<String, Bitmap> bitmapCache = new LruCache<String, Bitmap>();
For determining the initial size of the cache, it is good practice to determine the size based on the total memory
available on the device. For determining the available memory you can the MemoryClass. This is demonstrated
by the following code.
int memClass = ( ( ActivityManager) activity.getSystemService(
Context.ACTIVITY_SERVICE ) ).getMemoryClass(); int cacheSize = 1024 * 1024 *
memClass / 8; LruCache cache = new LruCache<String, Bitmap>( cacheSize );
3.2. Cleaning up your cache
As of API 14 you can override the onTrimMemory() method in Android components. This method is called by the
Android system asking you to cleanup your memory in case the Android system requires resources for foreground
processes.
And To more information visit:android course online

More Related Content

What's hot

Effective Numerical Computation in NumPy and SciPy
Effective Numerical Computation in NumPy and SciPyEffective Numerical Computation in NumPy and SciPy
Effective Numerical Computation in NumPy and SciPyKimikazu Kato
 
Implementation of Computational Algorithms using Parallel Programming
Implementation of Computational Algorithms using Parallel ProgrammingImplementation of Computational Algorithms using Parallel Programming
Implementation of Computational Algorithms using Parallel Programmingijtsrd
 
Pointer Events in Canvas
Pointer Events in CanvasPointer Events in Canvas
Pointer Events in Canvasdeanhudson
 
Streaming Python on Hadoop
Streaming Python on HadoopStreaming Python on Hadoop
Streaming Python on HadoopVivian S. Zhang
 
DPLYR package in R
DPLYR package in RDPLYR package in R
DPLYR package in RBimba Pawar
 
Intro to ggplot2 - Sheffield R Users Group, Feb 2015
Intro to ggplot2 - Sheffield R Users Group, Feb 2015Intro to ggplot2 - Sheffield R Users Group, Feb 2015
Intro to ggplot2 - Sheffield R Users Group, Feb 2015Paul Richards
 
Dynamic memory Allocation in c language
Dynamic memory Allocation in c languageDynamic memory Allocation in c language
Dynamic memory Allocation in c languagekiran Patel
 
Dynamic Memory Allocation(DMA)
Dynamic Memory Allocation(DMA)Dynamic Memory Allocation(DMA)
Dynamic Memory Allocation(DMA)Kamal Acharya
 
Js info vis_toolkit
Js info vis_toolkitJs info vis_toolkit
Js info vis_toolkitnikhilyagnic
 
16 dynamic-memory-allocation
16 dynamic-memory-allocation16 dynamic-memory-allocation
16 dynamic-memory-allocationRohit Shrivastava
 
Handling Numeric Attributes in Hoeffding Trees
Handling Numeric Attributes in Hoeffding TreesHandling Numeric Attributes in Hoeffding Trees
Handling Numeric Attributes in Hoeffding Treesbutest
 
Dynamic memory allocation in c language
Dynamic memory allocation in c languageDynamic memory allocation in c language
Dynamic memory allocation in c languagetanmaymodi4
 
Elegant Graphics for Data Analysis with ggplot2
Elegant Graphics for Data Analysis with ggplot2Elegant Graphics for Data Analysis with ggplot2
Elegant Graphics for Data Analysis with ggplot2yannabraham
 
Effective machine learning_with_tpu
Effective machine learning_with_tpuEffective machine learning_with_tpu
Effective machine learning_with_tpuAthul Suresh
 
Dynamic memory allocation in c
Dynamic memory allocation in cDynamic memory allocation in c
Dynamic memory allocation in clavanya marichamy
 
Extreme Scale Breadth-First Search on Supercomputers
Extreme Scale Breadth-First Search on SupercomputersExtreme Scale Breadth-First Search on Supercomputers
Extreme Scale Breadth-First Search on SupercomputersToyotaro Suzumura
 

What's hot (18)

Effective Numerical Computation in NumPy and SciPy
Effective Numerical Computation in NumPy and SciPyEffective Numerical Computation in NumPy and SciPy
Effective Numerical Computation in NumPy and SciPy
 
Implementation of Computational Algorithms using Parallel Programming
Implementation of Computational Algorithms using Parallel ProgrammingImplementation of Computational Algorithms using Parallel Programming
Implementation of Computational Algorithms using Parallel Programming
 
Pointer Events in Canvas
Pointer Events in CanvasPointer Events in Canvas
Pointer Events in Canvas
 
Streaming Python on Hadoop
Streaming Python on HadoopStreaming Python on Hadoop
Streaming Python on Hadoop
 
Memory allocation in c
Memory allocation in cMemory allocation in c
Memory allocation in c
 
DPLYR package in R
DPLYR package in RDPLYR package in R
DPLYR package in R
 
Intro to ggplot2 - Sheffield R Users Group, Feb 2015
Intro to ggplot2 - Sheffield R Users Group, Feb 2015Intro to ggplot2 - Sheffield R Users Group, Feb 2015
Intro to ggplot2 - Sheffield R Users Group, Feb 2015
 
Dynamic memory Allocation in c language
Dynamic memory Allocation in c languageDynamic memory Allocation in c language
Dynamic memory Allocation in c language
 
Dynamic Memory Allocation(DMA)
Dynamic Memory Allocation(DMA)Dynamic Memory Allocation(DMA)
Dynamic Memory Allocation(DMA)
 
Js info vis_toolkit
Js info vis_toolkitJs info vis_toolkit
Js info vis_toolkit
 
16 dynamic-memory-allocation
16 dynamic-memory-allocation16 dynamic-memory-allocation
16 dynamic-memory-allocation
 
Handling Numeric Attributes in Hoeffding Trees
Handling Numeric Attributes in Hoeffding TreesHandling Numeric Attributes in Hoeffding Trees
Handling Numeric Attributes in Hoeffding Trees
 
Dynamic memory allocation in c language
Dynamic memory allocation in c languageDynamic memory allocation in c language
Dynamic memory allocation in c language
 
Ae31225230
Ae31225230Ae31225230
Ae31225230
 
Elegant Graphics for Data Analysis with ggplot2
Elegant Graphics for Data Analysis with ggplot2Elegant Graphics for Data Analysis with ggplot2
Elegant Graphics for Data Analysis with ggplot2
 
Effective machine learning_with_tpu
Effective machine learning_with_tpuEffective machine learning_with_tpu
Effective machine learning_with_tpu
 
Dynamic memory allocation in c
Dynamic memory allocation in cDynamic memory allocation in c
Dynamic memory allocation in c
 
Extreme Scale Breadth-First Search on Supercomputers
Extreme Scale Breadth-First Search on SupercomputersExtreme Scale Breadth-First Search on Supercomputers
Extreme Scale Breadth-First Search on Supercomputers
 

Similar to Android memory and performance optimization

Android ui tips & tricks
Android ui tips & tricksAndroid ui tips & tricks
Android ui tips & tricksShem Magnezi
 
Android UI Tips & Tricks
Android UI Tips & TricksAndroid UI Tips & Tricks
Android UI Tips & TricksDroidConTLV
 
performance optimization: Memory
performance optimization: Memoryperformance optimization: Memory
performance optimization: Memory晓东 杜
 
Android - Displaying images
Android - Displaying imagesAndroid - Displaying images
Android - Displaying imagesMatteo Bonifazi
 
Cascading talk in Etsy (http://www.meetup.com/cascading/events/169390262/)
Cascading talk in Etsy (http://www.meetup.com/cascading/events/169390262/)Cascading talk in Etsy (http://www.meetup.com/cascading/events/169390262/)
Cascading talk in Etsy (http://www.meetup.com/cascading/events/169390262/)Jyotirmoy Sundi
 
Implementing of classical synchronization problem by using semaphores
Implementing of classical synchronization problem by using semaphoresImplementing of classical synchronization problem by using semaphores
Implementing of classical synchronization problem by using semaphoresGowtham Reddy
 
Getting started with ES6
Getting started with ES6Getting started with ES6
Getting started with ES6Nitay Neeman
 
From Zero to Hero – Web Performance
From Zero to Hero – Web PerformanceFrom Zero to Hero – Web Performance
From Zero to Hero – Web PerformanceSebastian Springer
 
Things you can find in the plan cache
Things you can find in the plan cacheThings you can find in the plan cache
Things you can find in the plan cachesqlserver.co.il
 
A so common questions and answers
A so common questions and answersA so common questions and answers
A so common questions and answersAmit Sharma
 
computer notes - Data Structures - 1
computer notes - Data Structures - 1computer notes - Data Structures - 1
computer notes - Data Structures - 1ecomputernotes
 
Android development training programme , Day 3
Android development training programme , Day 3Android development training programme , Day 3
Android development training programme , Day 3DHIRAJ PRAVIN
 
Mobile Developer Summit 2012, Pune
Mobile Developer Summit 2012, PuneMobile Developer Summit 2012, Pune
Mobile Developer Summit 2012, PuneBhuvan Khanna
 
An eternal question of timing
An eternal question of timingAn eternal question of timing
An eternal question of timingPVS-Studio
 
High Performance Ajax Applications 1197671494632682 2
High Performance Ajax Applications 1197671494632682 2High Performance Ajax Applications 1197671494632682 2
High Performance Ajax Applications 1197671494632682 2Niti Chotkaew
 
High Performance Ajax Applications
High Performance Ajax ApplicationsHigh Performance Ajax Applications
High Performance Ajax ApplicationsJulien Lecomte
 
Taking advantage of the Amazon Web Services (AWS) Family
Taking advantage of the Amazon Web Services (AWS) FamilyTaking advantage of the Amazon Web Services (AWS) Family
Taking advantage of the Amazon Web Services (AWS) FamilyBen Hall
 

Similar to Android memory and performance optimization (20)

Android ui tips & tricks
Android ui tips & tricksAndroid ui tips & tricks
Android ui tips & tricks
 
Android UI Tips & Tricks
Android UI Tips & TricksAndroid UI Tips & Tricks
Android UI Tips & Tricks
 
performance optimization: Memory
performance optimization: Memoryperformance optimization: Memory
performance optimization: Memory
 
Android - Displaying images
Android - Displaying imagesAndroid - Displaying images
Android - Displaying images
 
Cascading talk in Etsy (http://www.meetup.com/cascading/events/169390262/)
Cascading talk in Etsy (http://www.meetup.com/cascading/events/169390262/)Cascading talk in Etsy (http://www.meetup.com/cascading/events/169390262/)
Cascading talk in Etsy (http://www.meetup.com/cascading/events/169390262/)
 
Implementing of classical synchronization problem by using semaphores
Implementing of classical synchronization problem by using semaphoresImplementing of classical synchronization problem by using semaphores
Implementing of classical synchronization problem by using semaphores
 
J2SE 5
J2SE 5J2SE 5
J2SE 5
 
Getting started with ES6
Getting started with ES6Getting started with ES6
Getting started with ES6
 
From Zero to Hero – Web Performance
From Zero to Hero – Web PerformanceFrom Zero to Hero – Web Performance
From Zero to Hero – Web Performance
 
Things you can find in the plan cache
Things you can find in the plan cacheThings you can find in the plan cache
Things you can find in the plan cache
 
A so common questions and answers
A so common questions and answersA so common questions and answers
A so common questions and answers
 
computer notes - Data Structures - 1
computer notes - Data Structures - 1computer notes - Data Structures - 1
computer notes - Data Structures - 1
 
Smart material - Unit 3 (2).pdf
Smart material - Unit 3 (2).pdfSmart material - Unit 3 (2).pdf
Smart material - Unit 3 (2).pdf
 
Smart material - Unit 3 (1).pdf
Smart material - Unit 3 (1).pdfSmart material - Unit 3 (1).pdf
Smart material - Unit 3 (1).pdf
 
Android development training programme , Day 3
Android development training programme , Day 3Android development training programme , Day 3
Android development training programme , Day 3
 
Mobile Developer Summit 2012, Pune
Mobile Developer Summit 2012, PuneMobile Developer Summit 2012, Pune
Mobile Developer Summit 2012, Pune
 
An eternal question of timing
An eternal question of timingAn eternal question of timing
An eternal question of timing
 
High Performance Ajax Applications 1197671494632682 2
High Performance Ajax Applications 1197671494632682 2High Performance Ajax Applications 1197671494632682 2
High Performance Ajax Applications 1197671494632682 2
 
High Performance Ajax Applications
High Performance Ajax ApplicationsHigh Performance Ajax Applications
High Performance Ajax Applications
 
Taking advantage of the Amazon Web Services (AWS) Family
Taking advantage of the Amazon Web Services (AWS) FamilyTaking advantage of the Amazon Web Services (AWS) Family
Taking advantage of the Amazon Web Services (AWS) Family
 

More from veeracynixit

Servicenow it management tools
Servicenow it management toolsServicenow it management tools
Servicenow it management toolsveeracynixit
 
Apache avro data serialization framework
Apache avro   data serialization frameworkApache avro   data serialization framework
Apache avro data serialization frameworkveeracynixit
 
Android memory and performance optimization
Android memory and performance optimizationAndroid memory and performance optimization
Android memory and performance optimizationveeracynixit
 
Big data overview of apache hadoop
Big data overview of apache hadoopBig data overview of apache hadoop
Big data overview of apache hadoopveeracynixit
 
Ios actions and outlets
Ios actions and outletsIos actions and outlets
Ios actions and outletsveeracynixit
 
New in Hadoop: You should know the Various File Format in Hadoop.
New in Hadoop: You should know the Various File Format in Hadoop.New in Hadoop: You should know the Various File Format in Hadoop.
New in Hadoop: You should know the Various File Format in Hadoop.veeracynixit
 
Ios actions and outlets
Ios actions and outletsIos actions and outlets
Ios actions and outletsveeracynixit
 
Big data overview of apache hadoop
Big data overview of apache hadoopBig data overview of apache hadoop
Big data overview of apache hadoopveeracynixit
 
Android memory and performance optimization
Android memory and performance optimizationAndroid memory and performance optimization
Android memory and performance optimizationveeracynixit
 
Data presentation and reporting cognos tm1
Data presentation and reporting cognos tm1Data presentation and reporting cognos tm1
Data presentation and reporting cognos tm1veeracynixit
 

More from veeracynixit (10)

Servicenow it management tools
Servicenow it management toolsServicenow it management tools
Servicenow it management tools
 
Apache avro data serialization framework
Apache avro   data serialization frameworkApache avro   data serialization framework
Apache avro data serialization framework
 
Android memory and performance optimization
Android memory and performance optimizationAndroid memory and performance optimization
Android memory and performance optimization
 
Big data overview of apache hadoop
Big data overview of apache hadoopBig data overview of apache hadoop
Big data overview of apache hadoop
 
Ios actions and outlets
Ios actions and outletsIos actions and outlets
Ios actions and outlets
 
New in Hadoop: You should know the Various File Format in Hadoop.
New in Hadoop: You should know the Various File Format in Hadoop.New in Hadoop: You should know the Various File Format in Hadoop.
New in Hadoop: You should know the Various File Format in Hadoop.
 
Ios actions and outlets
Ios actions and outletsIos actions and outlets
Ios actions and outlets
 
Big data overview of apache hadoop
Big data overview of apache hadoopBig data overview of apache hadoop
Big data overview of apache hadoop
 
Android memory and performance optimization
Android memory and performance optimizationAndroid memory and performance optimization
Android memory and performance optimization
 
Data presentation and reporting cognos tm1
Data presentation and reporting cognos tm1Data presentation and reporting cognos tm1
Data presentation and reporting cognos tm1
 

Recently uploaded

SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...Sapna Thakur
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...anjaliyadav012327
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...fonyou31
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 

Recently uploaded (20)

SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 

Android memory and performance optimization

  • 1. Downloaded from: justpaste.it/85hq5 Android memory and performance optimization Android memory and performance optimization. This tutorial describes how to optimize the usage of memory and optimize your performance in your Android application. The tutorial is based on Android Studio,android studio course 1. Programming tips for providing highly responsive and fast Android applications 1.1. Why you should be careful with Android resources Android devices have less power than standard desktop or notebook computers. For this reason you must be careful with memory consumption. Especially on Android devices before Android 5.0 you want to avoid triggering the garbage collector of the Java virtual machine. This results in a freeze of the Android runtime for about 200 ms. This can be a notable delay, if the user is, for example, scrolling down a list. 1.2. Avoid unnecessary object allocation Avoid creating unnecessary objects, especially in expensive places. Reuse objects if possible. Creating unnecessary objects triggers the garbage collection more frequently, and this should be avoided. For example avoid object creating in loops or in the onDraw() method of your custom view. 1.3. Use efficient data structures Android provides several implementations of Sparse*Array classes. Consider the following code. Map<Integer, String> map = new HashMap<Integer, String>(); Using this code results in unnecessary Integer objects created. Android provides data structures which are more efficient for mapping values to other objects. If possible use these objects, they avoid object creation as in the case of using HashMap. Object creation can be expensive and should be avoided to reduce the number of times the garbage collector needs to run. The table give examples for SparseArrays. Table 1. Efficient memory structures Memory structure Description SparseArray<E> Maps integers to Objects, avoid the creation of Integer objects. SparseBooleanArray Maps integers to booleans. SparseIntArray Maps integers to integers
  • 2. To improve the above example, prefer to use the following data structure. SparseArray<String> map = new SparseArray<String>(); map.put(1, "Hello"); 2. Handling bitmaps Bitmaps can allocate lots of memory if loaded at full size. It is recommended to load the bitmaps in the desired size into memory. Assume you have an application which displays an image in 100x100 dp, you should load the image in exactly this size. A common way is to first measure the bitmap without loading it via a flag passed to the BitmapFactory. // instruct BitmapFactory to only the bounds and type of the image BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeResource(getResources(), R.id.myimage, options); // get width and height int imageHeight = options.outHeight; int imageWidth = options.outWidth; // type of the image String imageType = options.outMimeType; Afterwards you can load the scaled version of the image. Android is really good in scaling images by a power of two. You can use the following method (from the official Android documentation) to calculate the scale factor on a basis of 2. public static Bitmap decodeBitmapWithGiveSizeFromResource(Resources res, int resId, int reqWidth, int reqHeight) { // First decode with inJustDecodeBounds=true to check dimensions final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeResource(res, resId, options); // Calculate inSampleSize options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); // Decode bitmap with inSampleSize set options.inJustDecodeBounds = false; return BitmapFactory.decodeResource(res, resId, options); } public static int calculateInSampleSize( BitmapFactory.Options options, int reqWidth, int reqHeight) { // Raw height and width of image final int height = options.outHeight; final int width = options.outWidth; int inSampleSize = 1; if (height > reqHeight || width > reqWidth) { final int halfHeight = height / 2; final int halfWidth = width / 2; // Calculate the largest inSampleSize value that is a power of 2 and keeps both // height and width larger than the requested height and width. while ((halfHeight / inSampleSize) > reqHeight && (halfWidth / inSampleSize) > reqWidth) { inSampleSize *= 2; } } return inSampleSize; } This method can be used to assign the image to a view as demonstrated in the following example. viewWidth = imageView.getWidth(); viewHeight = imageView.getHeight(); imageView. imageView.setImageBitmap( decodeSampledBitmapFromResource(getResources(), R.id.myimage, viewWidth, viewHeight)); 3. Using caches 3.1. Using a cache A cache allows reusing objects which are expensive to create. If you load on object into memory, you can think of this as a cache for the object. For example, if you downloading images from the Internet to display them in a list you should hold them in memory to avoid that you download them several times.
  • 3. At some point you need to recycle some of your objects, otherwise you run out of memory. A good approach to do this, is to recycle the objects which have not been used the longest in your application. The Android platform provides the LruCache class, as of API 12 (or in the support-v4 library). The LruCache class provides a _least recently used cache _ (LRU cache) cache implementation. A LRU cache keeps track of the usage of its members. It has a given size and if this size is exceeded, it removes the items which have not be accessed the longest. This behavior is depicted in the following graphic. The following example code demonstrates a possible implementation of the LruCache class for caching images. public class ImageCache extends LruCache<String, Bitmap> { public ImageCache( int maxSize ) { super( maxSize ); } @Override protected int sizeOf( String key, Bitmap value ) { return value.getByteCount(); } @Override protected void entryRemoved( boolean evicted, String key, Bitmap oldValue, Bitmap newValue ) { oldValue.recycle(); } } Its usage is simple and demonstrated by the following example code. LruCache<String, Bitmap> bitmapCache = new LruCache<String, Bitmap>(); For determining the initial size of the cache, it is good practice to determine the size based on the total memory available on the device. For determining the available memory you can the MemoryClass. This is demonstrated by the following code. int memClass = ( ( ActivityManager) activity.getSystemService( Context.ACTIVITY_SERVICE ) ).getMemoryClass(); int cacheSize = 1024 * 1024 * memClass / 8; LruCache cache = new LruCache<String, Bitmap>( cacheSize ); 3.2. Cleaning up your cache As of API 14 you can override the onTrimMemory() method in Android components. This method is called by the Android system asking you to cleanup your memory in case the Android system requires resources for foreground processes.
  • 4. And To more information visit:android course online