SlideShare a Scribd company logo
Memory
memory leaks
memory churns
Best practices
Don't use a bigger primitive type if you don't
really need it: never use long, float, or double if
you can represent the number with an integer.
Data types
Autoboxing
should be avoided as much as possible
Sparse array family
The number of objects you are dealing with is below a thousand and you are
not going to do a lot of additions and deletions
You are using collections of maps with few items, but lots of iterations
SparseArray
LongSparseArray
SparseIntArray
SparseLongArray
SparseBooleanArray
ArrayMap
Array & Collections
Array
Enhanced for loop syntax is
the fastest way
Enum
static final integer values
Constants
should be static and final
memory savings
avoid initialization in the Java compiler <clinit> method. Object management
Create fewer temporary objects, as they are often garbage collected,
avoid instantiating unnecessary objects, as they are expensive for memory
and computational performance.
StringBuffer
StringBuilder
thread safe
To avoid this unnecessary waste of memory, if you know an estimation
of the string capacity you are dealing with
work on character arrays
String concatenation
Local variables
extract that object from the method
only instantiated once and it's available throughout the life cycle of the class object
Streams
incorrect closeTWR
Memory patterns
The object pool pattern
AsyncTask worker thread
RecyclerView recycled views
limit garbage collection
avoid memory churns
The FlyWeight pattern
expensive creation objects
reduce the load into memory by saving the state shared by all of the objects
Android component leaks
Activities
There is a strong reference between the activity and every
single contained view
static classes
static fields with activity dependencies
singletons
keyword this inside the activity code
strong reference to an object with a longer lifetime.
Context.getApplicationContext()
Non-static inner classes
set the inner class as a static one
provide the reference to that
use a weaker reference to achieve cleaner memory management
Singletons
use a WeakReference inside singleton
Anonymous inner classes
Handlers
Services
handler.postDelayed
anonymous inner classes, let's export that class, setting it as static
handler.removeCallbacksAndMessages(null);
Use IntentService every time you can because of the automatic nalization and because this way you don't risk creating memory leaks with services.
make sure that the Service is finished as soon as it completes its task.
The memory API
Never use the largeHeap attribute inside the Android manifest file to avoid OutOfMemoryError
ComponentCallback2
@Override
public void onTrimMemory(int level) {
switch (level) {
case TRIM_MEMORY_COMPLETE:
//app invisible - mem low - lru bottom
case TRIM_MEMORY_MODERATE:
//app invisible - mem low - lru medium
case TRIM_MEMORY_BACKGROUND:
//app invisible - mem low - lru top
case TRIM_MEMORY_UI_HIDDEN:
//app invisible - lru top
case TRIM_MEMORY_RUNNING_CRITICAL:
//app visible - mem critical - lru top
case TRIM_MEMORY_RUNNING_LOW:
//app visible - mem low - lru top
case TRIM_MEMORY_RUNNING_MODERATE:
//app visible - mem moderate - lru top
break;
}
}
onTrimMemory
LogCat
if the behavior of our application is correct.
Dalvik
D/dalvikvm: <GcReason> <AmountFreed>, <HeapStats>, <ExternalMemoryStats>, <PauseTime>
GC_CONCURRENT: It follows the GC event when the heap needs to be cleared.
GC_FOR_MALLOC: It follows the request of allocation of new memory, but there is not enough space to do it.
GC_HPROF_DUMP_HEAP: It follows a debug request to profile the heap. We will see what this means in the following pages.
GC_EXPLICIT: It follows a forced explicit request of System.gc() that, as we mentioned, should be avoided.
GC_EXTERNAL_ALLOC: It follows a request for external memory. This can happen only on devices lower or equal to Android Gingerbread (API Level 10), because in those devices, memory has different entries, but for later devices the memory is handled in the heap as a whole.
D/dalvikvm(9932): GC_CONCURRENT freed 1394K, 14% free 32193K/37262K, external 18524K/24185K, paused 2ms
ART
I/art: <GcReason> <GcName> <ObjectsFreed>(<SizeFreed>) AllocSpace Objects, <LargeObjectsFreed>(<LargeObjectSizeFreed>) <HeapStats> LOS objects, <PauseTimes>
Concurrent: It follows a concurrent GC event. This kind of event is executed in a different thread from the allocating one, so this one doesn't force the other application threads to stop, including the UI thread.
Alloc: It follows the request for the allocation of new memory, but there is not enough space to do it. This time, all the application threads are blocked until the garbage collection ends.
Explicit: It follows a forced explicit request of System.gc() that should be avoided for ART as well as for Dalvik.
NativeAlloc: It follows the request for memory by native allocations.
CollectorTransition: It follows the garbage collector switch on low memory devices.
HomogenousSpaceCompact: It follows the need of the system to reduce memory usage and to defragment the heap.
DisableMovingGc: It follows the collection block after a call to a particular internal method, called GetPrimitiveArrayCritical.
HeapTrim: It follows the collection block because a heap trim isn't finished.
I/art : Explicit concurrent mark sweep GC freed 125742(6MB) AllocSpace objects, 34(576KB) LOS objects, 22% free, 25MB/32MB, paused 1.621ms total 73.285ms
The ActivityManager API
setWatchHeapLimit
clearWatchHeapLimit
https://developer.android.com/studio/profile/allocation-tracker-walkthru.html
https://developer.android.com/studio/profile/heap-viewer-walkthru.html
Getting a sense of how your app allocates and frees memory.
Identifying memory leaks
call stack
size allocating code
types of objects
how many
sizes
https://developer.android.com/studio/profile/am-memory.html
slowness might be related to excessive garbage collection events
crashes may be related to running out of memory
Memory Monitor
Heap Viewer
Allocation Tracker
compare the heap dumps
creates multiple times but doesn’t destroy
growing memory leak
large arrays
https://developer.android.com/studio/profile/investigate-ram.html
https://developer.android.com/studio/profile/am-allocation.html
object types
Analyzer Tasks
leaked activities
duplicate strings
View
List
for > while > Iterator
private void iteratorCycle(List<String> list) {
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
String stemp = iterator.next();
}
}
private void whileCycle(List<String> list) {
int j = 0;
while (j < list.size()) {
String stemp = (String) list.get(j);
j++;
}
}
private void forCycle(List<String> list) {
for (int i = 0; i < list.size(); i++) {
String stemp = (String) list.get(i);
}
}
private void classicCycle(Dummy[] dummies) {
int sum = 0;
for (int i = 0; i < dummies.length; ++i) {
sum += dummies[i].dummy;
}
}
private void fasterCycle(Dummy[] dummies) {
int sum = 0;
int len = dummies.length;
for (int i = 0; i < len; ++i) {
sum += dummies[i].dummy;
}
}
private void enhancedCycle(Dummy[] dummies) {
int sum = 0;
for (Dummy a : dummies) {
sum += a.dummy;
}
}
java.lang.Byte
java.lang.Short
java.lang.Integer
java.lang.Long
java.lang.Float
java.lang.Double
java.lang.Boolean
java.lang.Character
byte: 8 bits
short: 16 bits
int: 32 bits
long: 64 bits
float: 32 bits
double: 64 bits
boolean: 8 bits, but it depends on the virtual machine
char: 16 bits
CPU calculation performance cost memory saving
HashMap
memory wasteCPU operations faster
avoid autoboxing be careful autoboxing
Compaction Resize
define type compile check
use annotation to have a limited number of values
new too many object
Good:
Bad:
Fix:
Basic
Iterate speed
Flow
Key
Runnable

More Related Content

Similar to performance optimization: Memory

Memory Leaks in Android Applications
Memory Leaks in Android ApplicationsMemory Leaks in Android Applications
Memory Leaks in Android Applications
Lokesh Ponnada
 
Efficient Memory and Thread Management in Highly Parallel Java Applications
Efficient Memory and Thread Management in Highly Parallel Java ApplicationsEfficient Memory and Thread Management in Highly Parallel Java Applications
Efficient Memory and Thread Management in Highly Parallel Java Applications
Phillip Koza
 
Java Garbage Collection, Monitoring, and Tuning
Java Garbage Collection, Monitoring, and TuningJava Garbage Collection, Monitoring, and Tuning
Java Garbage Collection, Monitoring, and TuningCarol McDonald
 
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
 
Performance Tuning - Memory leaks, Thread deadlocks, JDK tools
Performance Tuning -  Memory leaks, Thread deadlocks, JDK toolsPerformance Tuning -  Memory leaks, Thread deadlocks, JDK tools
Performance Tuning - Memory leaks, Thread deadlocks, JDK tools
Haribabu Nandyal Padmanaban
 
Java programing considering performance
Java programing considering performanceJava programing considering performance
Java programing considering performance
Roger Xia
 
Mobile Developer Summit 2012, Pune
Mobile Developer Summit 2012, PuneMobile Developer Summit 2012, Pune
Mobile Developer Summit 2012, PuneBhuvan Khanna
 
Exploring .NET memory management (iSense)
Exploring .NET memory management (iSense)Exploring .NET memory management (iSense)
Exploring .NET memory management (iSense)
Maarten Balliauw
 
Android programming -_pushing_the_limits
Android programming -_pushing_the_limitsAndroid programming -_pushing_the_limits
Android programming -_pushing_the_limitsDroidcon Berlin
 
Designing and coding Series 40 Java apps for high performance
Designing and coding Series 40 Java apps for high performanceDesigning and coding Series 40 Java apps for high performance
Designing and coding Series 40 Java apps for high performance
Microsoft Mobile Developer
 
Garbage collection
Garbage collectionGarbage collection
Garbage collection
Somya Bagai
 
DotNetFest - Let’s refresh our memory! Memory management in .NET
DotNetFest - Let’s refresh our memory! Memory management in .NETDotNetFest - Let’s refresh our memory! Memory management in .NET
DotNetFest - Let’s refresh our memory! Memory management in .NET
Maarten Balliauw
 
Memory Leak In java
Memory Leak In javaMemory Leak In java
Memory Leak In java
Mindfire Solutions
 
Memory Leaks on Android
Memory Leaks on AndroidMemory Leaks on Android
Memory Leaks on Android
Omri Erez
 
JetBrains Day Seoul - Exploring .NET’s memory management – a trip down memory...
JetBrains Day Seoul - Exploring .NET’s memory management – a trip down memory...JetBrains Day Seoul - Exploring .NET’s memory management – a trip down memory...
JetBrains Day Seoul - Exploring .NET’s memory management – a trip down memory...
Maarten Balliauw
 
C# Unit 2 notes
C# Unit 2 notesC# Unit 2 notes
C# Unit 2 notes
Sudarshan Dhondaley
 
Code Quality Management iOS
Code Quality Management iOSCode Quality Management iOS
Code Quality Management iOS
Arpit Kulsreshtha
 
Android Memory Management
Android Memory ManagementAndroid Memory Management
Android Memory Management
Sadmankabirsoumik
 
Exploring .NET memory management - JetBrains webinar
Exploring .NET memory management - JetBrains webinarExploring .NET memory management - JetBrains webinar
Exploring .NET memory management - JetBrains webinar
Maarten Balliauw
 
.NET Fest 2018. Maarten Balliauw. Let’s refresh our memory! Memory management...
.NET Fest 2018. Maarten Balliauw. Let’s refresh our memory! Memory management....NET Fest 2018. Maarten Balliauw. Let’s refresh our memory! Memory management...
.NET Fest 2018. Maarten Balliauw. Let’s refresh our memory! Memory management...
NETFest
 

Similar to performance optimization: Memory (20)

Memory Leaks in Android Applications
Memory Leaks in Android ApplicationsMemory Leaks in Android Applications
Memory Leaks in Android Applications
 
Efficient Memory and Thread Management in Highly Parallel Java Applications
Efficient Memory and Thread Management in Highly Parallel Java ApplicationsEfficient Memory and Thread Management in Highly Parallel Java Applications
Efficient Memory and Thread Management in Highly Parallel Java Applications
 
Java Garbage Collection, Monitoring, and Tuning
Java Garbage Collection, Monitoring, and TuningJava Garbage Collection, Monitoring, and Tuning
Java Garbage Collection, Monitoring, and Tuning
 
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 ...
 
Performance Tuning - Memory leaks, Thread deadlocks, JDK tools
Performance Tuning -  Memory leaks, Thread deadlocks, JDK toolsPerformance Tuning -  Memory leaks, Thread deadlocks, JDK tools
Performance Tuning - Memory leaks, Thread deadlocks, JDK tools
 
Java programing considering performance
Java programing considering performanceJava programing considering performance
Java programing considering performance
 
Mobile Developer Summit 2012, Pune
Mobile Developer Summit 2012, PuneMobile Developer Summit 2012, Pune
Mobile Developer Summit 2012, Pune
 
Exploring .NET memory management (iSense)
Exploring .NET memory management (iSense)Exploring .NET memory management (iSense)
Exploring .NET memory management (iSense)
 
Android programming -_pushing_the_limits
Android programming -_pushing_the_limitsAndroid programming -_pushing_the_limits
Android programming -_pushing_the_limits
 
Designing and coding Series 40 Java apps for high performance
Designing and coding Series 40 Java apps for high performanceDesigning and coding Series 40 Java apps for high performance
Designing and coding Series 40 Java apps for high performance
 
Garbage collection
Garbage collectionGarbage collection
Garbage collection
 
DotNetFest - Let’s refresh our memory! Memory management in .NET
DotNetFest - Let’s refresh our memory! Memory management in .NETDotNetFest - Let’s refresh our memory! Memory management in .NET
DotNetFest - Let’s refresh our memory! Memory management in .NET
 
Memory Leak In java
Memory Leak In javaMemory Leak In java
Memory Leak In java
 
Memory Leaks on Android
Memory Leaks on AndroidMemory Leaks on Android
Memory Leaks on Android
 
JetBrains Day Seoul - Exploring .NET’s memory management – a trip down memory...
JetBrains Day Seoul - Exploring .NET’s memory management – a trip down memory...JetBrains Day Seoul - Exploring .NET’s memory management – a trip down memory...
JetBrains Day Seoul - Exploring .NET’s memory management – a trip down memory...
 
C# Unit 2 notes
C# Unit 2 notesC# Unit 2 notes
C# Unit 2 notes
 
Code Quality Management iOS
Code Quality Management iOSCode Quality Management iOS
Code Quality Management iOS
 
Android Memory Management
Android Memory ManagementAndroid Memory Management
Android Memory Management
 
Exploring .NET memory management - JetBrains webinar
Exploring .NET memory management - JetBrains webinarExploring .NET memory management - JetBrains webinar
Exploring .NET memory management - JetBrains webinar
 
.NET Fest 2018. Maarten Balliauw. Let’s refresh our memory! Memory management...
.NET Fest 2018. Maarten Balliauw. Let’s refresh our memory! Memory management....NET Fest 2018. Maarten Balliauw. Let’s refresh our memory! Memory management...
.NET Fest 2018. Maarten Balliauw. Let’s refresh our memory! Memory management...
 

More from 晓东 杜

Stability issues of user space
Stability issues of user spaceStability issues of user space
Stability issues of user space
晓东 杜
 
performance optimization: UI
performance optimization: UIperformance optimization: UI
performance optimization: UI
晓东 杜
 
Embedded Android
Embedded AndroidEmbedded Android
Embedded Android
晓东 杜
 
Openwrt wireless
Openwrt wirelessOpenwrt wireless
Openwrt wireless
晓东 杜
 
Openwrt startup
Openwrt startupOpenwrt startup
Openwrt startup
晓东 杜
 
Openwrt frontend backend
Openwrt frontend backendOpenwrt frontend backend
Openwrt frontend backend
晓东 杜
 
DevOps at DUDU
DevOps at DUDUDevOps at DUDU
DevOps at DUDU
晓东 杜
 

More from 晓东 杜 (7)

Stability issues of user space
Stability issues of user spaceStability issues of user space
Stability issues of user space
 
performance optimization: UI
performance optimization: UIperformance optimization: UI
performance optimization: UI
 
Embedded Android
Embedded AndroidEmbedded Android
Embedded Android
 
Openwrt wireless
Openwrt wirelessOpenwrt wireless
Openwrt wireless
 
Openwrt startup
Openwrt startupOpenwrt startup
Openwrt startup
 
Openwrt frontend backend
Openwrt frontend backendOpenwrt frontend backend
Openwrt frontend backend
 
DevOps at DUDU
DevOps at DUDUDevOps at DUDU
DevOps at DUDU
 

Recently uploaded

Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
rickgrimesss22
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Natan Silnitsky
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
Google
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
Adele Miller
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
vrstrong314
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
Ortus Solutions, Corp
 
Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
Donna Lenk
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
Juraj Vysvader
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Globus
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
Globus
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
Georgi Kodinov
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Shahin Sheidaei
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Anthony Dahanne
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
wottaspaceseo
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
WSO2
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
Tendenci - The Open Source AMS (Association Management Software)
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
IES VE
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
Max Andersen
 
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdfEnhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Jay Das
 

Recently uploaded (20)

Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
 
Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
 
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdfEnhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
 

performance optimization: Memory

  • 1. Memory memory leaks memory churns Best practices Don't use a bigger primitive type if you don't really need it: never use long, float, or double if you can represent the number with an integer. Data types Autoboxing should be avoided as much as possible Sparse array family The number of objects you are dealing with is below a thousand and you are not going to do a lot of additions and deletions You are using collections of maps with few items, but lots of iterations SparseArray LongSparseArray SparseIntArray SparseLongArray SparseBooleanArray ArrayMap Array & Collections Array Enhanced for loop syntax is the fastest way Enum static final integer values Constants should be static and final memory savings avoid initialization in the Java compiler <clinit> method. Object management Create fewer temporary objects, as they are often garbage collected, avoid instantiating unnecessary objects, as they are expensive for memory and computational performance. StringBuffer StringBuilder thread safe To avoid this unnecessary waste of memory, if you know an estimation of the string capacity you are dealing with work on character arrays String concatenation Local variables extract that object from the method only instantiated once and it's available throughout the life cycle of the class object Streams incorrect closeTWR Memory patterns The object pool pattern AsyncTask worker thread RecyclerView recycled views limit garbage collection avoid memory churns The FlyWeight pattern expensive creation objects reduce the load into memory by saving the state shared by all of the objects Android component leaks Activities There is a strong reference between the activity and every single contained view static classes static fields with activity dependencies singletons keyword this inside the activity code strong reference to an object with a longer lifetime. Context.getApplicationContext() Non-static inner classes set the inner class as a static one provide the reference to that use a weaker reference to achieve cleaner memory management Singletons use a WeakReference inside singleton Anonymous inner classes Handlers Services handler.postDelayed anonymous inner classes, let's export that class, setting it as static handler.removeCallbacksAndMessages(null); Use IntentService every time you can because of the automatic nalization and because this way you don't risk creating memory leaks with services. make sure that the Service is finished as soon as it completes its task. The memory API Never use the largeHeap attribute inside the Android manifest file to avoid OutOfMemoryError ComponentCallback2 @Override public void onTrimMemory(int level) { switch (level) { case TRIM_MEMORY_COMPLETE: //app invisible - mem low - lru bottom case TRIM_MEMORY_MODERATE: //app invisible - mem low - lru medium case TRIM_MEMORY_BACKGROUND: //app invisible - mem low - lru top case TRIM_MEMORY_UI_HIDDEN: //app invisible - lru top case TRIM_MEMORY_RUNNING_CRITICAL: //app visible - mem critical - lru top case TRIM_MEMORY_RUNNING_LOW: //app visible - mem low - lru top case TRIM_MEMORY_RUNNING_MODERATE: //app visible - mem moderate - lru top break; } } onTrimMemory LogCat if the behavior of our application is correct. Dalvik D/dalvikvm: <GcReason> <AmountFreed>, <HeapStats>, <ExternalMemoryStats>, <PauseTime> GC_CONCURRENT: It follows the GC event when the heap needs to be cleared. GC_FOR_MALLOC: It follows the request of allocation of new memory, but there is not enough space to do it. GC_HPROF_DUMP_HEAP: It follows a debug request to profile the heap. We will see what this means in the following pages. GC_EXPLICIT: It follows a forced explicit request of System.gc() that, as we mentioned, should be avoided. GC_EXTERNAL_ALLOC: It follows a request for external memory. This can happen only on devices lower or equal to Android Gingerbread (API Level 10), because in those devices, memory has different entries, but for later devices the memory is handled in the heap as a whole. D/dalvikvm(9932): GC_CONCURRENT freed 1394K, 14% free 32193K/37262K, external 18524K/24185K, paused 2ms ART I/art: <GcReason> <GcName> <ObjectsFreed>(<SizeFreed>) AllocSpace Objects, <LargeObjectsFreed>(<LargeObjectSizeFreed>) <HeapStats> LOS objects, <PauseTimes> Concurrent: It follows a concurrent GC event. This kind of event is executed in a different thread from the allocating one, so this one doesn't force the other application threads to stop, including the UI thread. Alloc: It follows the request for the allocation of new memory, but there is not enough space to do it. This time, all the application threads are blocked until the garbage collection ends. Explicit: It follows a forced explicit request of System.gc() that should be avoided for ART as well as for Dalvik. NativeAlloc: It follows the request for memory by native allocations. CollectorTransition: It follows the garbage collector switch on low memory devices. HomogenousSpaceCompact: It follows the need of the system to reduce memory usage and to defragment the heap. DisableMovingGc: It follows the collection block after a call to a particular internal method, called GetPrimitiveArrayCritical. HeapTrim: It follows the collection block because a heap trim isn't finished. I/art : Explicit concurrent mark sweep GC freed 125742(6MB) AllocSpace objects, 34(576KB) LOS objects, 22% free, 25MB/32MB, paused 1.621ms total 73.285ms The ActivityManager API setWatchHeapLimit clearWatchHeapLimit https://developer.android.com/studio/profile/allocation-tracker-walkthru.html https://developer.android.com/studio/profile/heap-viewer-walkthru.html Getting a sense of how your app allocates and frees memory. Identifying memory leaks call stack size allocating code types of objects how many sizes https://developer.android.com/studio/profile/am-memory.html slowness might be related to excessive garbage collection events crashes may be related to running out of memory Memory Monitor Heap Viewer Allocation Tracker compare the heap dumps creates multiple times but doesn’t destroy growing memory leak large arrays https://developer.android.com/studio/profile/investigate-ram.html https://developer.android.com/studio/profile/am-allocation.html object types Analyzer Tasks leaked activities duplicate strings View List for > while > Iterator private void iteratorCycle(List<String> list) { Iterator<String> iterator = list.iterator(); while (iterator.hasNext()) { String stemp = iterator.next(); } } private void whileCycle(List<String> list) { int j = 0; while (j < list.size()) { String stemp = (String) list.get(j); j++; } } private void forCycle(List<String> list) { for (int i = 0; i < list.size(); i++) { String stemp = (String) list.get(i); } } private void classicCycle(Dummy[] dummies) { int sum = 0; for (int i = 0; i < dummies.length; ++i) { sum += dummies[i].dummy; } } private void fasterCycle(Dummy[] dummies) { int sum = 0; int len = dummies.length; for (int i = 0; i < len; ++i) { sum += dummies[i].dummy; } } private void enhancedCycle(Dummy[] dummies) { int sum = 0; for (Dummy a : dummies) { sum += a.dummy; } } java.lang.Byte java.lang.Short java.lang.Integer java.lang.Long java.lang.Float java.lang.Double java.lang.Boolean java.lang.Character byte: 8 bits short: 16 bits int: 32 bits long: 64 bits float: 32 bits double: 64 bits boolean: 8 bits, but it depends on the virtual machine char: 16 bits CPU calculation performance cost memory saving HashMap memory wasteCPU operations faster avoid autoboxing be careful autoboxing Compaction Resize define type compile check use annotation to have a limited number of values new too many object Good: Bad: Fix: Basic Iterate speed Flow Key Runnable