SlideShare a Scribd company logo
How to memory efficient Code?
Ram Lakshmanan
Architect – GCeasy.io, fastThread.io, HeapHero.io
Confoo 2019
Do I need to care about memory?
It’s very cheap!
1970s
1 Byte = 1 $
2019
FRACTION OF COST
Here is my case: Memory is not cheap!
Memory saturates first.
Other resources are
partially/under utilized.
3. Storage
4. Network
1. CPU
2. Memory
Do you know how much memory applications wastes?
30 – 90%
You can't optimize, what you can't
measure
A famous saying
How to measure wasted memory?
Step 1: Capture Heap dumps in production*
https://blog.heaphero.io/2017/10/13/how-to-capture-java-heap-dumps-7-options/
Step 2: Analyze with HeapHero: https://heaphero.io
Reports amount of memory wasted, code triggering it, recommendations to fix.
* - if possible
Analyze real-world example
String Duplication
What is duplicate String?
String s1 = new String("Hello World");
String s2 = new String("Hello World");
System.out.println(s1.equals(s2)); // prints 'true'
System.out.println((s1 == s2)); // prints 'false'
Solution 1: intern()
String s1 = new String("Hello World").intern();
String s2 = new String("Hello World").intern();
System.out.println(s1.equals(s2)); // prints 'true'
System.out.println((s1 == s2)); // prints 'true'
>>> s1 = intern(’Hello World')
Java
Python
How intern() works?
“Hello World”
s1
s2
String pool
String s1 = new String("Hello World").intern();
String s2 = new String("Hello World").intern();
Solution 2: UseStringDeduplication
• -XX:+UseStringDeduplication
• Works only with
• G1 GC algorithm
• Java 8 update 20
• Real life case study:
https://blog.gceasy.io/2018/07/17/disappointing-story-on-memory-
optimization/
Long lived objects (-XX:StringDeduplicationAgeThreshold=3)
• Check GC pause time impact
Solution 3: Use String literals
public static final String HELLO_WORLD = “Hello World”;
Solution 4: Avoid creating strings
In DB store data as primitive types:
user
id
Name …. country
1 Joe Libson …. Canada
2 Nathan Ray …. Canada
3 Chris Mang …. USA
4 Erik Pilz …. USA
5 Lakshmi
Singh
…. India
user
id
Name …. country
1 Joe Libson …. 2
2 Nathan Ray …. 2
3 Chris Mang …. 1
4 Erik Pilz …. 1
5 Lakshmi
Singh
…. 124
Inefficiency in collections
Inefficiency in Collections
List<User> users = new ArrayList<>();
users.add(user);
2 54 6 7 8 1093
wasted
11
ArrayList underlyingly maintains
Object[]
initial capacity = 10
1 2 54 6 7 8 1093
Inefficiency in Collections
wasted
List<User> users = new ArrayList<>();
for (int counter = 1; counter <= 11; ++counter) {
users.add(user);
}
1 2 54 6 7 8 1093 11 12 1514 17 18 201913 16
1 2 54 6 7 8 93 11 12 1514 17 18 201913 16 21 22 2524 26 27 28 2923 31 32 3534 37 38 403933 3630
wasted
10
for (int counter = 1; counter <= 21; ++counter) {
users.add(user);
}
Recommendation 1: use capacity
new ArrayList<>(3);
new ArrayList<>();
Recommendation 2: lazy initialization
private List<User> users = new ArrayList<>();
public void addUser(User user) {
users.add(user);
}
private List<User> users;
public void addUser(User user) {
if (users == null) {
users = new ArrayList<>();
}
users.add(user);
}
Recommendation 3: avoid clear()
List<User> users = new ArrayList<>();
users = null;
List<User> users = new ArrayList<>();
users.clear();
Let’s understand overhead of an
Object
Object overhead
public class User {
private String name;
private int age;
private float weight;
}
new User();
Object Header
name
age
weight
12 bytes
4 bytes
4 bytes
4 bytes
Fixed overhead
1. Virtual method invocation
2. ‘synchronized’ object lock
3. Garbage collection
4. Object book keeping
24 bytes
Boxed numbers: java.lang.Integer
• int: 4 bytes
• java.lang.Integer: 16 bytes
Data is 4 bytes, object overhead is 12 bytes
Yesterday’s key note: 2 instance variables/class
public class User {
private int field1;
private int field2;
private int field3;
:
private int field10;
}
public class User {
private Object1 obj1;
private Object2 obj2;
}
public class Object1 {
private int field1;
private Object3 obj3;
}
public class Object2 {
private int field2;
private Object4 obj4;
}
public class Object3 {
private int field3;
private Object5 obj5;
}
public class Object4 {
private int field4;
private Object6 obj6;
}52 bytes
i.e. 12 bytes header + (10 ints* 4 bytes) public class Object5 {
private int field5;
private Object6 obj7;
}
public class Object6 {
private int field6;
private Object3 obj8;
}
public class Object7 {
private int field7;
private Object4 obj9;
}
public class Object8 {
private int field8;
private int field9;
}
public class Object9 {
private int field10;
}
196 bytes (~4x more needed)
= 10 object headers * 12 + (10 ints * 4 bytes)
+ (9 object references * 4)
How all memory is wasted?
1. Duplicate Strings: https://heaphero.io/heap-recommendations/duplicate-strings.html
2. Wrong memory size settings
3. Inefficient Collections: http://heaphero.io/heap-recommendations/inefficient-collections.html
4. Duplicate Objects: https://heaphero.io/heap-recommendations/duplicate-objects.html
5. Duplicate arrays: https://heaphero.io/heap-recommendations/duplicate-primitive-arrays.html
6. Inefficient arrays: https://heaphero.io/heap-recommendations/inefficient-primitive-arrays.html
7. Objects waiting for finalization: https://heaphero.io/heap-recommendations/objects-waiting-
finalization.html
8. Boxed numbers: https://heaphero.io/heap-recommendations/boxed-numbers.html
9. Object Headers: https://heaphero.io/heap-recommendations/object-headers.html
Reduce computing cost
Better Response time
Reduce Garbage Collection Pause Time
Optimizing memory
Fascinating to read
Thank you!!
ram@tier1app.com
Ram Lakshmanan
@tier1app
https://www.linkedin.com/company/gceasy
Any Questions
Deck will be published in:
http://blog.heaphero.io

More Related Content

What's hot

Shooting the troubles: Crashes, Slowdowns, CPU Spikes
Shooting the troubles: Crashes, Slowdowns, CPU SpikesShooting the troubles: Crashes, Slowdowns, CPU Spikes
Shooting the troubles: Crashes, Slowdowns, CPU Spikes
Tier1 app
 
System Calls
System CallsSystem Calls
System Calls
David Evans
 
Making a Process
Making a ProcessMaking a Process
Making a Process
David Evans
 
Putting a Fork in Fork (Linux Process and Memory Management)
Putting a Fork in Fork (Linux Process and Memory Management)Putting a Fork in Fork (Linux Process and Memory Management)
Putting a Fork in Fork (Linux Process and Memory Management)
David Evans
 
Crossing into Kernel Space
Crossing into Kernel SpaceCrossing into Kernel Space
Crossing into Kernel Space
David Evans
 
Everything you wanted to know about Stack Traces and Heap Dumps
Everything you wanted to know about Stack Traces and Heap DumpsEverything you wanted to know about Stack Traces and Heap Dumps
Everything you wanted to know about Stack Traces and Heap Dumps
Andrei Pangin
 
Silicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsSilicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM Mechanics
Azul Systems, Inc.
 
The Art of JVM Profiling
The Art of JVM ProfilingThe Art of JVM Profiling
The Art of JVM Profiling
Andrei Pangin
 
Thread dump troubleshooting
Thread dump troubleshootingThread dump troubleshooting
Thread dump troubleshooting
Jerry Chan
 
Scheduling
SchedulingScheduling
Scheduling
David Evans
 
Refactoring for testability c++
Refactoring for testability c++Refactoring for testability c++
Refactoring for testability c++
Dimitrios Platis
 
Do we need Unsafe in Java?
Do we need Unsafe in Java?Do we need Unsafe in Java?
Do we need Unsafe in Java?
Andrei Pangin
 
jvm goes to big data
jvm goes to big datajvm goes to big data
jvm goes to big data
srisatish ambati
 
Cassandra is great but how do I test my application?
Cassandra is great but how do I test my application?Cassandra is great but how do I test my application?
Cassandra is great but how do I test my application?
Christopher Batey
 
Choosing the right parallel compute architecture
Choosing the right parallel compute architecture Choosing the right parallel compute architecture
Choosing the right parallel compute architecture
corehard_by
 
Java Heap Dump Analysis Primer
Java Heap Dump Analysis PrimerJava Heap Dump Analysis Primer
Java Heap Dump Analysis Primer
Kyle Hodgson
 
Down to Stack Traces, up from Heap Dumps
Down to Stack Traces, up from Heap DumpsDown to Stack Traces, up from Heap Dumps
Down to Stack Traces, up from Heap Dumps
Andrei Pangin
 
Counter Wars (JEEConf 2016)
Counter Wars (JEEConf 2016)Counter Wars (JEEConf 2016)
Counter Wars (JEEConf 2016)
Alexey Fyodorov
 
Feldo: Function Event Listing and Dynamic Observing for Detecting and Prevent...
Feldo: Function Event Listing and Dynamic Observing for Detecting and Prevent...Feldo: Function Event Listing and Dynamic Observing for Detecting and Prevent...
Feldo: Function Event Listing and Dynamic Observing for Detecting and Prevent...
Tzung-Bi Shih
 
marko_go_in_badoo
marko_go_in_badoomarko_go_in_badoo
marko_go_in_badoo
Marko Kevac
 

What's hot (20)

Shooting the troubles: Crashes, Slowdowns, CPU Spikes
Shooting the troubles: Crashes, Slowdowns, CPU SpikesShooting the troubles: Crashes, Slowdowns, CPU Spikes
Shooting the troubles: Crashes, Slowdowns, CPU Spikes
 
System Calls
System CallsSystem Calls
System Calls
 
Making a Process
Making a ProcessMaking a Process
Making a Process
 
Putting a Fork in Fork (Linux Process and Memory Management)
Putting a Fork in Fork (Linux Process and Memory Management)Putting a Fork in Fork (Linux Process and Memory Management)
Putting a Fork in Fork (Linux Process and Memory Management)
 
Crossing into Kernel Space
Crossing into Kernel SpaceCrossing into Kernel Space
Crossing into Kernel Space
 
Everything you wanted to know about Stack Traces and Heap Dumps
Everything you wanted to know about Stack Traces and Heap DumpsEverything you wanted to know about Stack Traces and Heap Dumps
Everything you wanted to know about Stack Traces and Heap Dumps
 
Silicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsSilicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM Mechanics
 
The Art of JVM Profiling
The Art of JVM ProfilingThe Art of JVM Profiling
The Art of JVM Profiling
 
Thread dump troubleshooting
Thread dump troubleshootingThread dump troubleshooting
Thread dump troubleshooting
 
Scheduling
SchedulingScheduling
Scheduling
 
Refactoring for testability c++
Refactoring for testability c++Refactoring for testability c++
Refactoring for testability c++
 
Do we need Unsafe in Java?
Do we need Unsafe in Java?Do we need Unsafe in Java?
Do we need Unsafe in Java?
 
jvm goes to big data
jvm goes to big datajvm goes to big data
jvm goes to big data
 
Cassandra is great but how do I test my application?
Cassandra is great but how do I test my application?Cassandra is great but how do I test my application?
Cassandra is great but how do I test my application?
 
Choosing the right parallel compute architecture
Choosing the right parallel compute architecture Choosing the right parallel compute architecture
Choosing the right parallel compute architecture
 
Java Heap Dump Analysis Primer
Java Heap Dump Analysis PrimerJava Heap Dump Analysis Primer
Java Heap Dump Analysis Primer
 
Down to Stack Traces, up from Heap Dumps
Down to Stack Traces, up from Heap DumpsDown to Stack Traces, up from Heap Dumps
Down to Stack Traces, up from Heap Dumps
 
Counter Wars (JEEConf 2016)
Counter Wars (JEEConf 2016)Counter Wars (JEEConf 2016)
Counter Wars (JEEConf 2016)
 
Feldo: Function Event Listing and Dynamic Observing for Detecting and Prevent...
Feldo: Function Event Listing and Dynamic Observing for Detecting and Prevent...Feldo: Function Event Listing and Dynamic Observing for Detecting and Prevent...
Feldo: Function Event Listing and Dynamic Observing for Detecting and Prevent...
 
marko_go_in_badoo
marko_go_in_badoomarko_go_in_badoo
marko_go_in_badoo
 

Similar to How to write memory efficient code?

Intro to Python
Intro to PythonIntro to Python
Intro to Python
Daniel Greenfeld
 
Approximate "Now" is Better Than Accurate "Later"
Approximate "Now" is Better Than Accurate "Later"Approximate "Now" is Better Than Accurate "Later"
Approximate "Now" is Better Than Accurate "Later"
NUS-ISS
 
Memory management
Memory managementMemory management
Memory management
Kuban Dzhakipov
 
Intro
IntroIntro
Why learn Internals?
Why learn Internals?Why learn Internals?
Why learn Internals?
Shaul Rosenzwieg
 
Fantastic caches and where to find them
Fantastic caches and where to find themFantastic caches and where to find them
Fantastic caches and where to find them
Alexey Tokar
 
Memory Management In Python The Basics
Memory Management In Python The BasicsMemory Management In Python The Basics
Memory Management In Python The Basics
Nina Zakharenko
 
Optimizing mobile applications - Ian Dundore, Mark Harkness
Optimizing mobile applications - Ian Dundore, Mark HarknessOptimizing mobile applications - Ian Dundore, Mark Harkness
Optimizing mobile applications - Ian Dundore, Mark Harkness
ozlael ozlael
 
0507 057 01 98 * Adana Cukurova Klima Servisleri
0507 057 01 98 * Adana Cukurova Klima Servisleri0507 057 01 98 * Adana Cukurova Klima Servisleri
Python Interview Questions | Python Interview Questions And Answers | Python ...
Python Interview Questions | Python Interview Questions And Answers | Python ...Python Interview Questions | Python Interview Questions And Answers | Python ...
Python Interview Questions | Python Interview Questions And Answers | Python ...
Simplilearn
 
Everything You Always Wanted to Know About Memory in Python - But Were Afraid...
Everything You Always Wanted to Know About Memory in Python - But Were Afraid...Everything You Always Wanted to Know About Memory in Python - But Were Afraid...
Everything You Always Wanted to Know About Memory in Python - But Were Afraid...
Piotr Przymus
 
High Performance With Java
High Performance With JavaHigh Performance With Java
High Performance With Java
malduarte
 
Pycon2017 instagram keynote
Pycon2017 instagram keynotePycon2017 instagram keynote
Pycon2017 instagram keynote
Lisa Guo
 
Celery: The Distributed Task Queue
Celery: The Distributed Task QueueCelery: The Distributed Task Queue
Celery: The Distributed Task Queue
Richard Leland
 
Talking trash
Talking trashTalking trash
Talking trash
michael.labriola
 
Everything You Always Wanted to Know About Memory in Python But Were Afraid t...
Everything You Always Wanted to Know About Memory in Python But Were Afraid t...Everything You Always Wanted to Know About Memory in Python But Were Afraid t...
Everything You Always Wanted to Know About Memory in Python But Were Afraid t...
Piotr Przymus
 
SEMLA_logging_infra
SEMLA_logging_infraSEMLA_logging_infra
SEMLA_logging_infra
swy351
 
Micrometrics to forecast performance tsunamis
Micrometrics to forecast performance tsunamisMicrometrics to forecast performance tsunamis
Micrometrics to forecast performance tsunamis
Tier1app
 
Fuzzing - Part 1
Fuzzing - Part 1Fuzzing - Part 1
Fuzzing - Part 1
UTD Computer Security Group
 
THE PERFORMANCE COMPARISON OF A BRUTEFORCE PASSWORD CRACKING ALGORITHM USING ...
THE PERFORMANCE COMPARISON OF A BRUTEFORCE PASSWORD CRACKING ALGORITHM USING ...THE PERFORMANCE COMPARISON OF A BRUTEFORCE PASSWORD CRACKING ALGORITHM USING ...
THE PERFORMANCE COMPARISON OF A BRUTEFORCE PASSWORD CRACKING ALGORITHM USING ...
ijsptm
 

Similar to How to write memory efficient code? (20)

Intro to Python
Intro to PythonIntro to Python
Intro to Python
 
Approximate "Now" is Better Than Accurate "Later"
Approximate "Now" is Better Than Accurate "Later"Approximate "Now" is Better Than Accurate "Later"
Approximate "Now" is Better Than Accurate "Later"
 
Memory management
Memory managementMemory management
Memory management
 
Intro
IntroIntro
Intro
 
Why learn Internals?
Why learn Internals?Why learn Internals?
Why learn Internals?
 
Fantastic caches and where to find them
Fantastic caches and where to find themFantastic caches and where to find them
Fantastic caches and where to find them
 
Memory Management In Python The Basics
Memory Management In Python The BasicsMemory Management In Python The Basics
Memory Management In Python The Basics
 
Optimizing mobile applications - Ian Dundore, Mark Harkness
Optimizing mobile applications - Ian Dundore, Mark HarknessOptimizing mobile applications - Ian Dundore, Mark Harkness
Optimizing mobile applications - Ian Dundore, Mark Harkness
 
0507 057 01 98 * Adana Cukurova Klima Servisleri
0507 057 01 98 * Adana Cukurova Klima Servisleri0507 057 01 98 * Adana Cukurova Klima Servisleri
0507 057 01 98 * Adana Cukurova Klima Servisleri
 
Python Interview Questions | Python Interview Questions And Answers | Python ...
Python Interview Questions | Python Interview Questions And Answers | Python ...Python Interview Questions | Python Interview Questions And Answers | Python ...
Python Interview Questions | Python Interview Questions And Answers | Python ...
 
Everything You Always Wanted to Know About Memory in Python - But Were Afraid...
Everything You Always Wanted to Know About Memory in Python - But Were Afraid...Everything You Always Wanted to Know About Memory in Python - But Were Afraid...
Everything You Always Wanted to Know About Memory in Python - But Were Afraid...
 
High Performance With Java
High Performance With JavaHigh Performance With Java
High Performance With Java
 
Pycon2017 instagram keynote
Pycon2017 instagram keynotePycon2017 instagram keynote
Pycon2017 instagram keynote
 
Celery: The Distributed Task Queue
Celery: The Distributed Task QueueCelery: The Distributed Task Queue
Celery: The Distributed Task Queue
 
Talking trash
Talking trashTalking trash
Talking trash
 
Everything You Always Wanted to Know About Memory in Python But Were Afraid t...
Everything You Always Wanted to Know About Memory in Python But Were Afraid t...Everything You Always Wanted to Know About Memory in Python But Were Afraid t...
Everything You Always Wanted to Know About Memory in Python But Were Afraid t...
 
SEMLA_logging_infra
SEMLA_logging_infraSEMLA_logging_infra
SEMLA_logging_infra
 
Micrometrics to forecast performance tsunamis
Micrometrics to forecast performance tsunamisMicrometrics to forecast performance tsunamis
Micrometrics to forecast performance tsunamis
 
Fuzzing - Part 1
Fuzzing - Part 1Fuzzing - Part 1
Fuzzing - Part 1
 
THE PERFORMANCE COMPARISON OF A BRUTEFORCE PASSWORD CRACKING ALGORITHM USING ...
THE PERFORMANCE COMPARISON OF A BRUTEFORCE PASSWORD CRACKING ALGORITHM USING ...THE PERFORMANCE COMPARISON OF A BRUTEFORCE PASSWORD CRACKING ALGORITHM USING ...
THE PERFORMANCE COMPARISON OF A BRUTEFORCE PASSWORD CRACKING ALGORITHM USING ...
 

More from Tier1 app

DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSISDECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
Tier1 app
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
Tier1 app
 
Top-5-java-perf-problems-jax_mainz_2024.pptx
Top-5-java-perf-problems-jax_mainz_2024.pptxTop-5-java-perf-problems-jax_mainz_2024.pptx
Top-5-java-perf-problems-jax_mainz_2024.pptx
Tier1 app
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
Tier1 app
 
Effectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorEffectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryError
Tier1 app
 
Top-5-production-devconMunich-2023-v2.pptx
Top-5-production-devconMunich-2023-v2.pptxTop-5-production-devconMunich-2023-v2.pptx
Top-5-production-devconMunich-2023-v2.pptx
Tier1 app
 
predicting-m3-devopsconMunich-2023-v2.pptx
predicting-m3-devopsconMunich-2023-v2.pptxpredicting-m3-devopsconMunich-2023-v2.pptx
predicting-m3-devopsconMunich-2023-v2.pptx
Tier1 app
 
Top-5-production-devconMunich-2023.pptx
Top-5-production-devconMunich-2023.pptxTop-5-production-devconMunich-2023.pptx
Top-5-production-devconMunich-2023.pptx
Tier1 app
 
predicting-m3-devopsconMunich-2023.pptx
predicting-m3-devopsconMunich-2023.pptxpredicting-m3-devopsconMunich-2023.pptx
predicting-m3-devopsconMunich-2023.pptx
Tier1 app
 
Predicting Production Outages: Unleashing the Power of Micro-Metrics – ADDO C...
Predicting Production Outages: Unleashing the Power of Micro-Metrics – ADDO C...Predicting Production Outages: Unleashing the Power of Micro-Metrics – ADDO C...
Predicting Production Outages: Unleashing the Power of Micro-Metrics – ADDO C...
Tier1 app
 
7-JVM-arguments-JaxLondon-2023.pptx
7-JVM-arguments-JaxLondon-2023.pptx7-JVM-arguments-JaxLondon-2023.pptx
7-JVM-arguments-JaxLondon-2023.pptx
Tier1 app
 
Top-5-Performance-JaxLondon-2023.pptx
Top-5-Performance-JaxLondon-2023.pptxTop-5-Performance-JaxLondon-2023.pptx
Top-5-Performance-JaxLondon-2023.pptx
Tier1 app
 
16 ARTIFACTS TO CAPTURE WHEN YOUR CONTAINER APPLICATION IS IN TROUBLE
16 ARTIFACTS TO CAPTURE WHEN YOUR CONTAINER APPLICATION IS IN TROUBLE16 ARTIFACTS TO CAPTURE WHEN YOUR CONTAINER APPLICATION IS IN TROUBLE
16 ARTIFACTS TO CAPTURE WHEN YOUR CONTAINER APPLICATION IS IN TROUBLE
Tier1 app
 
MAJOR OUTAGES IN MAJOR ENTERPRISES
MAJOR OUTAGES IN MAJOR ENTERPRISESMAJOR OUTAGES IN MAJOR ENTERPRISES
MAJOR OUTAGES IN MAJOR ENTERPRISES
Tier1 app
 
KnowAPIs-UnknownPerf-confoo-2023 (1).pptx
KnowAPIs-UnknownPerf-confoo-2023 (1).pptxKnowAPIs-UnknownPerf-confoo-2023 (1).pptx
KnowAPIs-UnknownPerf-confoo-2023 (1).pptx
Tier1 app
 
memory-patterns-confoo-2023.pptx
memory-patterns-confoo-2023.pptxmemory-patterns-confoo-2023.pptx
memory-patterns-confoo-2023.pptx
Tier1 app
 
this-is-garbage-talk-2022.pptx
this-is-garbage-talk-2022.pptxthis-is-garbage-talk-2022.pptx
this-is-garbage-talk-2022.pptx
Tier1 app
 
millions-gc-jax-2022.pptx
millions-gc-jax-2022.pptxmillions-gc-jax-2022.pptx
millions-gc-jax-2022.pptx
Tier1 app
 
lets-crash-apps-jax-2022.pptx
lets-crash-apps-jax-2022.pptxlets-crash-apps-jax-2022.pptx
lets-crash-apps-jax-2022.pptx
Tier1 app
 
‘16 artifacts’ to capture when there is a production problem
‘16 artifacts’ to capture when there is a production problem‘16 artifacts’ to capture when there is a production problem
‘16 artifacts’ to capture when there is a production problem
Tier1 app
 

More from Tier1 app (20)

DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSISDECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
 
Top-5-java-perf-problems-jax_mainz_2024.pptx
Top-5-java-perf-problems-jax_mainz_2024.pptxTop-5-java-perf-problems-jax_mainz_2024.pptx
Top-5-java-perf-problems-jax_mainz_2024.pptx
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
Effectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorEffectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryError
 
Top-5-production-devconMunich-2023-v2.pptx
Top-5-production-devconMunich-2023-v2.pptxTop-5-production-devconMunich-2023-v2.pptx
Top-5-production-devconMunich-2023-v2.pptx
 
predicting-m3-devopsconMunich-2023-v2.pptx
predicting-m3-devopsconMunich-2023-v2.pptxpredicting-m3-devopsconMunich-2023-v2.pptx
predicting-m3-devopsconMunich-2023-v2.pptx
 
Top-5-production-devconMunich-2023.pptx
Top-5-production-devconMunich-2023.pptxTop-5-production-devconMunich-2023.pptx
Top-5-production-devconMunich-2023.pptx
 
predicting-m3-devopsconMunich-2023.pptx
predicting-m3-devopsconMunich-2023.pptxpredicting-m3-devopsconMunich-2023.pptx
predicting-m3-devopsconMunich-2023.pptx
 
Predicting Production Outages: Unleashing the Power of Micro-Metrics – ADDO C...
Predicting Production Outages: Unleashing the Power of Micro-Metrics – ADDO C...Predicting Production Outages: Unleashing the Power of Micro-Metrics – ADDO C...
Predicting Production Outages: Unleashing the Power of Micro-Metrics – ADDO C...
 
7-JVM-arguments-JaxLondon-2023.pptx
7-JVM-arguments-JaxLondon-2023.pptx7-JVM-arguments-JaxLondon-2023.pptx
7-JVM-arguments-JaxLondon-2023.pptx
 
Top-5-Performance-JaxLondon-2023.pptx
Top-5-Performance-JaxLondon-2023.pptxTop-5-Performance-JaxLondon-2023.pptx
Top-5-Performance-JaxLondon-2023.pptx
 
16 ARTIFACTS TO CAPTURE WHEN YOUR CONTAINER APPLICATION IS IN TROUBLE
16 ARTIFACTS TO CAPTURE WHEN YOUR CONTAINER APPLICATION IS IN TROUBLE16 ARTIFACTS TO CAPTURE WHEN YOUR CONTAINER APPLICATION IS IN TROUBLE
16 ARTIFACTS TO CAPTURE WHEN YOUR CONTAINER APPLICATION IS IN TROUBLE
 
MAJOR OUTAGES IN MAJOR ENTERPRISES
MAJOR OUTAGES IN MAJOR ENTERPRISESMAJOR OUTAGES IN MAJOR ENTERPRISES
MAJOR OUTAGES IN MAJOR ENTERPRISES
 
KnowAPIs-UnknownPerf-confoo-2023 (1).pptx
KnowAPIs-UnknownPerf-confoo-2023 (1).pptxKnowAPIs-UnknownPerf-confoo-2023 (1).pptx
KnowAPIs-UnknownPerf-confoo-2023 (1).pptx
 
memory-patterns-confoo-2023.pptx
memory-patterns-confoo-2023.pptxmemory-patterns-confoo-2023.pptx
memory-patterns-confoo-2023.pptx
 
this-is-garbage-talk-2022.pptx
this-is-garbage-talk-2022.pptxthis-is-garbage-talk-2022.pptx
this-is-garbage-talk-2022.pptx
 
millions-gc-jax-2022.pptx
millions-gc-jax-2022.pptxmillions-gc-jax-2022.pptx
millions-gc-jax-2022.pptx
 
lets-crash-apps-jax-2022.pptx
lets-crash-apps-jax-2022.pptxlets-crash-apps-jax-2022.pptx
lets-crash-apps-jax-2022.pptx
 
‘16 artifacts’ to capture when there is a production problem
‘16 artifacts’ to capture when there is a production problem‘16 artifacts’ to capture when there is a production problem
‘16 artifacts’ to capture when there is a production problem
 

Recently uploaded

Electric Fetus - Record Store Scavenger Hunt
Electric Fetus - Record Store Scavenger HuntElectric Fetus - Record Store Scavenger Hunt
Electric Fetus - Record Store Scavenger Hunt
RamseyBerglund
 
Bonku-Babus-Friend by Sathyajith Ray (9)
Bonku-Babus-Friend by Sathyajith Ray  (9)Bonku-Babus-Friend by Sathyajith Ray  (9)
Bonku-Babus-Friend by Sathyajith Ray (9)
nitinpv4ai
 
مصحف القراءات العشر أعد أحرف الخلاف سمير بسيوني.pdf
مصحف القراءات العشر   أعد أحرف الخلاف سمير بسيوني.pdfمصحف القراءات العشر   أعد أحرف الخلاف سمير بسيوني.pdf
مصحف القراءات العشر أعد أحرف الخلاف سمير بسيوني.pdf
سمير بسيوني
 
How to Fix [Errno 98] address already in use
How to Fix [Errno 98] address already in useHow to Fix [Errno 98] address already in use
How to Fix [Errno 98] address already in use
Celine George
 
How to Manage Reception Report in Odoo 17
How to Manage Reception Report in Odoo 17How to Manage Reception Report in Odoo 17
How to Manage Reception Report in Odoo 17
Celine George
 
Pharmaceutics Pharmaceuticals best of brub
Pharmaceutics Pharmaceuticals best of brubPharmaceutics Pharmaceuticals best of brub
Pharmaceutics Pharmaceuticals best of brub
danielkiash986
 
CIS 4200-02 Group 1 Final Project Report (1).pdf
CIS 4200-02 Group 1 Final Project Report (1).pdfCIS 4200-02 Group 1 Final Project Report (1).pdf
CIS 4200-02 Group 1 Final Project Report (1).pdf
blueshagoo1
 
The basics of sentences session 7pptx.pptx
The basics of sentences session 7pptx.pptxThe basics of sentences session 7pptx.pptx
The basics of sentences session 7pptx.pptx
heathfieldcps1
 
220711130088 Sumi Basak Virtual University EPC 3.pptx
220711130088 Sumi Basak Virtual University EPC 3.pptx220711130088 Sumi Basak Virtual University EPC 3.pptx
220711130088 Sumi Basak Virtual University EPC 3.pptx
Kalna College
 
Contiguity Of Various Message Forms - Rupam Chandra.pptx
Contiguity Of Various Message Forms - Rupam Chandra.pptxContiguity Of Various Message Forms - Rupam Chandra.pptx
Contiguity Of Various Message Forms - Rupam Chandra.pptx
Kalna College
 
CHUYÊN ĐỀ ÔN TẬP VÀ PHÁT TRIỂN CÂU HỎI TRONG ĐỀ MINH HỌA THI TỐT NGHIỆP THPT ...
CHUYÊN ĐỀ ÔN TẬP VÀ PHÁT TRIỂN CÂU HỎI TRONG ĐỀ MINH HỌA THI TỐT NGHIỆP THPT ...CHUYÊN ĐỀ ÔN TẬP VÀ PHÁT TRIỂN CÂU HỎI TRONG ĐỀ MINH HỌA THI TỐT NGHIỆP THPT ...
CHUYÊN ĐỀ ÔN TẬP VÀ PHÁT TRIỂN CÂU HỎI TRONG ĐỀ MINH HỌA THI TỐT NGHIỆP THPT ...
Nguyen Thanh Tu Collection
 
RESULTS OF THE EVALUATION QUESTIONNAIRE.pptx
RESULTS OF THE EVALUATION QUESTIONNAIRE.pptxRESULTS OF THE EVALUATION QUESTIONNAIRE.pptx
RESULTS OF THE EVALUATION QUESTIONNAIRE.pptx
zuzanka
 
HYPERTENSION - SLIDE SHARE PRESENTATION.
HYPERTENSION - SLIDE SHARE PRESENTATION.HYPERTENSION - SLIDE SHARE PRESENTATION.
HYPERTENSION - SLIDE SHARE PRESENTATION.
deepaannamalai16
 
A Visual Guide to 1 Samuel | A Tale of Two Hearts
A Visual Guide to 1 Samuel | A Tale of Two HeartsA Visual Guide to 1 Samuel | A Tale of Two Hearts
A Visual Guide to 1 Samuel | A Tale of Two Hearts
Steve Thomason
 
Wound healing PPT
Wound healing PPTWound healing PPT
Wound healing PPT
Jyoti Chand
 
Data Structure using C by Dr. K Adisesha .ppsx
Data Structure using C by Dr. K Adisesha .ppsxData Structure using C by Dr. K Adisesha .ppsx
Data Structure using C by Dr. K Adisesha .ppsx
Prof. Dr. K. Adisesha
 
A Free 200-Page eBook ~ Brain and Mind Exercise.pptx
A Free 200-Page eBook ~ Brain and Mind Exercise.pptxA Free 200-Page eBook ~ Brain and Mind Exercise.pptx
A Free 200-Page eBook ~ Brain and Mind Exercise.pptx
OH TEIK BIN
 
Observational Learning
Observational Learning Observational Learning
Observational Learning
sanamushtaq922
 
Andreas Schleicher presents PISA 2022 Volume III - Creative Thinking - 18 Jun...
Andreas Schleicher presents PISA 2022 Volume III - Creative Thinking - 18 Jun...Andreas Schleicher presents PISA 2022 Volume III - Creative Thinking - 18 Jun...
Andreas Schleicher presents PISA 2022 Volume III - Creative Thinking - 18 Jun...
EduSkills OECD
 
220711130083 SUBHASHREE RAKSHIT Internet resources for social science
220711130083 SUBHASHREE RAKSHIT  Internet resources for social science220711130083 SUBHASHREE RAKSHIT  Internet resources for social science
220711130083 SUBHASHREE RAKSHIT Internet resources for social science
Kalna College
 

Recently uploaded (20)

Electric Fetus - Record Store Scavenger Hunt
Electric Fetus - Record Store Scavenger HuntElectric Fetus - Record Store Scavenger Hunt
Electric Fetus - Record Store Scavenger Hunt
 
Bonku-Babus-Friend by Sathyajith Ray (9)
Bonku-Babus-Friend by Sathyajith Ray  (9)Bonku-Babus-Friend by Sathyajith Ray  (9)
Bonku-Babus-Friend by Sathyajith Ray (9)
 
مصحف القراءات العشر أعد أحرف الخلاف سمير بسيوني.pdf
مصحف القراءات العشر   أعد أحرف الخلاف سمير بسيوني.pdfمصحف القراءات العشر   أعد أحرف الخلاف سمير بسيوني.pdf
مصحف القراءات العشر أعد أحرف الخلاف سمير بسيوني.pdf
 
How to Fix [Errno 98] address already in use
How to Fix [Errno 98] address already in useHow to Fix [Errno 98] address already in use
How to Fix [Errno 98] address already in use
 
How to Manage Reception Report in Odoo 17
How to Manage Reception Report in Odoo 17How to Manage Reception Report in Odoo 17
How to Manage Reception Report in Odoo 17
 
Pharmaceutics Pharmaceuticals best of brub
Pharmaceutics Pharmaceuticals best of brubPharmaceutics Pharmaceuticals best of brub
Pharmaceutics Pharmaceuticals best of brub
 
CIS 4200-02 Group 1 Final Project Report (1).pdf
CIS 4200-02 Group 1 Final Project Report (1).pdfCIS 4200-02 Group 1 Final Project Report (1).pdf
CIS 4200-02 Group 1 Final Project Report (1).pdf
 
The basics of sentences session 7pptx.pptx
The basics of sentences session 7pptx.pptxThe basics of sentences session 7pptx.pptx
The basics of sentences session 7pptx.pptx
 
220711130088 Sumi Basak Virtual University EPC 3.pptx
220711130088 Sumi Basak Virtual University EPC 3.pptx220711130088 Sumi Basak Virtual University EPC 3.pptx
220711130088 Sumi Basak Virtual University EPC 3.pptx
 
Contiguity Of Various Message Forms - Rupam Chandra.pptx
Contiguity Of Various Message Forms - Rupam Chandra.pptxContiguity Of Various Message Forms - Rupam Chandra.pptx
Contiguity Of Various Message Forms - Rupam Chandra.pptx
 
CHUYÊN ĐỀ ÔN TẬP VÀ PHÁT TRIỂN CÂU HỎI TRONG ĐỀ MINH HỌA THI TỐT NGHIỆP THPT ...
CHUYÊN ĐỀ ÔN TẬP VÀ PHÁT TRIỂN CÂU HỎI TRONG ĐỀ MINH HỌA THI TỐT NGHIỆP THPT ...CHUYÊN ĐỀ ÔN TẬP VÀ PHÁT TRIỂN CÂU HỎI TRONG ĐỀ MINH HỌA THI TỐT NGHIỆP THPT ...
CHUYÊN ĐỀ ÔN TẬP VÀ PHÁT TRIỂN CÂU HỎI TRONG ĐỀ MINH HỌA THI TỐT NGHIỆP THPT ...
 
RESULTS OF THE EVALUATION QUESTIONNAIRE.pptx
RESULTS OF THE EVALUATION QUESTIONNAIRE.pptxRESULTS OF THE EVALUATION QUESTIONNAIRE.pptx
RESULTS OF THE EVALUATION QUESTIONNAIRE.pptx
 
HYPERTENSION - SLIDE SHARE PRESENTATION.
HYPERTENSION - SLIDE SHARE PRESENTATION.HYPERTENSION - SLIDE SHARE PRESENTATION.
HYPERTENSION - SLIDE SHARE PRESENTATION.
 
A Visual Guide to 1 Samuel | A Tale of Two Hearts
A Visual Guide to 1 Samuel | A Tale of Two HeartsA Visual Guide to 1 Samuel | A Tale of Two Hearts
A Visual Guide to 1 Samuel | A Tale of Two Hearts
 
Wound healing PPT
Wound healing PPTWound healing PPT
Wound healing PPT
 
Data Structure using C by Dr. K Adisesha .ppsx
Data Structure using C by Dr. K Adisesha .ppsxData Structure using C by Dr. K Adisesha .ppsx
Data Structure using C by Dr. K Adisesha .ppsx
 
A Free 200-Page eBook ~ Brain and Mind Exercise.pptx
A Free 200-Page eBook ~ Brain and Mind Exercise.pptxA Free 200-Page eBook ~ Brain and Mind Exercise.pptx
A Free 200-Page eBook ~ Brain and Mind Exercise.pptx
 
Observational Learning
Observational Learning Observational Learning
Observational Learning
 
Andreas Schleicher presents PISA 2022 Volume III - Creative Thinking - 18 Jun...
Andreas Schleicher presents PISA 2022 Volume III - Creative Thinking - 18 Jun...Andreas Schleicher presents PISA 2022 Volume III - Creative Thinking - 18 Jun...
Andreas Schleicher presents PISA 2022 Volume III - Creative Thinking - 18 Jun...
 
220711130083 SUBHASHREE RAKSHIT Internet resources for social science
220711130083 SUBHASHREE RAKSHIT  Internet resources for social science220711130083 SUBHASHREE RAKSHIT  Internet resources for social science
220711130083 SUBHASHREE RAKSHIT Internet resources for social science
 

How to write memory efficient code?

  • 1. How to memory efficient Code? Ram Lakshmanan Architect – GCeasy.io, fastThread.io, HeapHero.io Confoo 2019
  • 2. Do I need to care about memory? It’s very cheap! 1970s 1 Byte = 1 $ 2019 FRACTION OF COST
  • 3. Here is my case: Memory is not cheap! Memory saturates first. Other resources are partially/under utilized. 3. Storage 4. Network 1. CPU 2. Memory
  • 4. Do you know how much memory applications wastes? 30 – 90%
  • 5. You can't optimize, what you can't measure A famous saying
  • 6. How to measure wasted memory? Step 1: Capture Heap dumps in production* https://blog.heaphero.io/2017/10/13/how-to-capture-java-heap-dumps-7-options/ Step 2: Analyze with HeapHero: https://heaphero.io Reports amount of memory wasted, code triggering it, recommendations to fix. * - if possible
  • 9. What is duplicate String? String s1 = new String("Hello World"); String s2 = new String("Hello World"); System.out.println(s1.equals(s2)); // prints 'true' System.out.println((s1 == s2)); // prints 'false'
  • 10. Solution 1: intern() String s1 = new String("Hello World").intern(); String s2 = new String("Hello World").intern(); System.out.println(s1.equals(s2)); // prints 'true' System.out.println((s1 == s2)); // prints 'true' >>> s1 = intern(’Hello World') Java Python
  • 11. How intern() works? “Hello World” s1 s2 String pool String s1 = new String("Hello World").intern(); String s2 = new String("Hello World").intern();
  • 12. Solution 2: UseStringDeduplication • -XX:+UseStringDeduplication • Works only with • G1 GC algorithm • Java 8 update 20 • Real life case study: https://blog.gceasy.io/2018/07/17/disappointing-story-on-memory- optimization/ Long lived objects (-XX:StringDeduplicationAgeThreshold=3) • Check GC pause time impact
  • 13. Solution 3: Use String literals public static final String HELLO_WORLD = “Hello World”;
  • 14. Solution 4: Avoid creating strings In DB store data as primitive types: user id Name …. country 1 Joe Libson …. Canada 2 Nathan Ray …. Canada 3 Chris Mang …. USA 4 Erik Pilz …. USA 5 Lakshmi Singh …. India user id Name …. country 1 Joe Libson …. 2 2 Nathan Ray …. 2 3 Chris Mang …. 1 4 Erik Pilz …. 1 5 Lakshmi Singh …. 124
  • 16. Inefficiency in Collections List<User> users = new ArrayList<>(); users.add(user); 2 54 6 7 8 1093 wasted 11 ArrayList underlyingly maintains Object[] initial capacity = 10
  • 17. 1 2 54 6 7 8 1093 Inefficiency in Collections wasted List<User> users = new ArrayList<>(); for (int counter = 1; counter <= 11; ++counter) { users.add(user); } 1 2 54 6 7 8 1093 11 12 1514 17 18 201913 16 1 2 54 6 7 8 93 11 12 1514 17 18 201913 16 21 22 2524 26 27 28 2923 31 32 3534 37 38 403933 3630 wasted 10 for (int counter = 1; counter <= 21; ++counter) { users.add(user); }
  • 18. Recommendation 1: use capacity new ArrayList<>(3); new ArrayList<>();
  • 19. Recommendation 2: lazy initialization private List<User> users = new ArrayList<>(); public void addUser(User user) { users.add(user); } private List<User> users; public void addUser(User user) { if (users == null) { users = new ArrayList<>(); } users.add(user); }
  • 20. Recommendation 3: avoid clear() List<User> users = new ArrayList<>(); users = null; List<User> users = new ArrayList<>(); users.clear();
  • 22. Object overhead public class User { private String name; private int age; private float weight; } new User(); Object Header name age weight 12 bytes 4 bytes 4 bytes 4 bytes Fixed overhead 1. Virtual method invocation 2. ‘synchronized’ object lock 3. Garbage collection 4. Object book keeping 24 bytes
  • 23. Boxed numbers: java.lang.Integer • int: 4 bytes • java.lang.Integer: 16 bytes Data is 4 bytes, object overhead is 12 bytes
  • 24. Yesterday’s key note: 2 instance variables/class public class User { private int field1; private int field2; private int field3; : private int field10; } public class User { private Object1 obj1; private Object2 obj2; } public class Object1 { private int field1; private Object3 obj3; } public class Object2 { private int field2; private Object4 obj4; } public class Object3 { private int field3; private Object5 obj5; } public class Object4 { private int field4; private Object6 obj6; }52 bytes i.e. 12 bytes header + (10 ints* 4 bytes) public class Object5 { private int field5; private Object6 obj7; } public class Object6 { private int field6; private Object3 obj8; } public class Object7 { private int field7; private Object4 obj9; } public class Object8 { private int field8; private int field9; } public class Object9 { private int field10; } 196 bytes (~4x more needed) = 10 object headers * 12 + (10 ints * 4 bytes) + (9 object references * 4)
  • 25. How all memory is wasted? 1. Duplicate Strings: https://heaphero.io/heap-recommendations/duplicate-strings.html 2. Wrong memory size settings 3. Inefficient Collections: http://heaphero.io/heap-recommendations/inefficient-collections.html 4. Duplicate Objects: https://heaphero.io/heap-recommendations/duplicate-objects.html 5. Duplicate arrays: https://heaphero.io/heap-recommendations/duplicate-primitive-arrays.html 6. Inefficient arrays: https://heaphero.io/heap-recommendations/inefficient-primitive-arrays.html 7. Objects waiting for finalization: https://heaphero.io/heap-recommendations/objects-waiting- finalization.html 8. Boxed numbers: https://heaphero.io/heap-recommendations/boxed-numbers.html 9. Object Headers: https://heaphero.io/heap-recommendations/object-headers.html
  • 26. Reduce computing cost Better Response time Reduce Garbage Collection Pause Time Optimizing memory

Editor's Notes

  1. https://heaphero.io/my-heap-report.jsp?p=YXJjaGl2ZWQvMjAxOS8wMy8xNC8tLVRQQkUxLWhlYXBkdW1wLTE3XzA4XzE3XzEwXzMwLmJpbi5nei0zLTQ0LTE1Lmpzb24tLQ== https://heaphero.io/my-heap-report.jsp?p=YXJjaGl2ZWQvMjAxOS8wMy8xNC8tLVRQU1AxLWhlYXBkdW1wLTE3XzA4XzE3XzEwXzMwLmJpbi5nei0zLTI1LTI3Lmpzb24tLQ==