SlideShare uma empresa Scribd logo
1 de 28
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

Mais conteúdo relacionado

Mais procurados

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 SpikesTier1 app
 
Making a Process
Making a ProcessMaking a Process
Making a ProcessDavid 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 SpaceDavid 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 DumpsAndrei Pangin
 
Silicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsSilicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsAzul Systems, Inc.
 
The Art of JVM Profiling
The Art of JVM ProfilingThe Art of JVM Profiling
The Art of JVM ProfilingAndrei Pangin
 
Thread dump troubleshooting
Thread dump troubleshootingThread dump troubleshooting
Thread dump troubleshootingJerry Chan
 
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
 
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 PrimerKyle 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 DumpsAndrei 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_badooMarko Kevac
 

Mais procurados (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
 

Semelhante a How to write memory efficient code?

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
 
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 themAlexey Tokar
 
Memory Management In Python The Basics
Memory Management In Python The BasicsMemory Management In Python The Basics
Memory Management In Python The BasicsNina 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 Harknessozlael ozlael
 
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 Javamalduarte
 
Pycon2017 instagram keynote
Pycon2017 instagram keynotePycon2017 instagram keynote
Pycon2017 instagram keynoteLisa Guo
 
Celery: The Distributed Task Queue
Celery: The Distributed Task QueueCelery: The Distributed Task Queue
Celery: The Distributed Task QueueRichard Leland
 
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_infraswy351
 
Micrometrics to forecast performance tsunamis
Micrometrics to forecast performance tsunamisMicrometrics to forecast performance tsunamis
Micrometrics to forecast performance tsunamisTier1app
 
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
 

Semelhante a 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
 
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
 
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
 
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 ...
 

Mais de 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.pptxTier1 app
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
Effectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorEffectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorTier1 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.pptxTier1 app
 
predicting-m3-devopsconMunich-2023-v2.pptx
predicting-m3-devopsconMunich-2023-v2.pptxpredicting-m3-devopsconMunich-2023-v2.pptx
predicting-m3-devopsconMunich-2023-v2.pptxTier1 app
 
Top-5-production-devconMunich-2023.pptx
Top-5-production-devconMunich-2023.pptxTop-5-production-devconMunich-2023.pptx
Top-5-production-devconMunich-2023.pptxTier1 app
 
predicting-m3-devopsconMunich-2023.pptx
predicting-m3-devopsconMunich-2023.pptxpredicting-m3-devopsconMunich-2023.pptx
predicting-m3-devopsconMunich-2023.pptxTier1 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.pptxTier1 app
 
Top-5-Performance-JaxLondon-2023.pptx
Top-5-Performance-JaxLondon-2023.pptxTop-5-Performance-JaxLondon-2023.pptx
Top-5-Performance-JaxLondon-2023.pptxTier1 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 TROUBLETier1 app
 
MAJOR OUTAGES IN MAJOR ENTERPRISES
MAJOR OUTAGES IN MAJOR ENTERPRISESMAJOR OUTAGES IN MAJOR ENTERPRISES
MAJOR OUTAGES IN MAJOR ENTERPRISESTier1 app
 
KnowAPIs-UnknownPerf-confoo-2023 (1).pptx
KnowAPIs-UnknownPerf-confoo-2023 (1).pptxKnowAPIs-UnknownPerf-confoo-2023 (1).pptx
KnowAPIs-UnknownPerf-confoo-2023 (1).pptxTier1 app
 
memory-patterns-confoo-2023.pptx
memory-patterns-confoo-2023.pptxmemory-patterns-confoo-2023.pptx
memory-patterns-confoo-2023.pptxTier1 app
 
this-is-garbage-talk-2022.pptx
this-is-garbage-talk-2022.pptxthis-is-garbage-talk-2022.pptx
this-is-garbage-talk-2022.pptxTier1 app
 
millions-gc-jax-2022.pptx
millions-gc-jax-2022.pptxmillions-gc-jax-2022.pptx
millions-gc-jax-2022.pptxTier1 app
 
lets-crash-apps-jax-2022.pptx
lets-crash-apps-jax-2022.pptxlets-crash-apps-jax-2022.pptx
lets-crash-apps-jax-2022.pptxTier1 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 problemTier1 app
 
Lets crash-applications
Lets crash-applicationsLets crash-applications
Lets crash-applicationsTier1 app
 
7 habits of highly effective Performance Troubleshooters
7 habits of highly effective Performance Troubleshooters7 habits of highly effective Performance Troubleshooters
7 habits of highly effective Performance TroubleshootersTier1 app
 

Mais de Tier1 app (20)

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
 
Lets crash-applications
Lets crash-applicationsLets crash-applications
Lets crash-applications
 
7 habits of highly effective Performance Troubleshooters
7 habits of highly effective Performance Troubleshooters7 habits of highly effective Performance Troubleshooters
7 habits of highly effective Performance Troubleshooters
 

Último

HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxmarlenawright1
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxEsquimalt MFRC
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxCeline George
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxJisc
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxPooja Bhuva
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...Amil baba
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxJisc
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structuredhanjurrannsibayan2
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfDr Vijay Vishwakarma
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17Celine George
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxPooja Bhuva
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - Englishneillewis46
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the ClassroomPooky Knightsmith
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfSherif Taha
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Pooja Bhuva
 

Último (20)

HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 

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

Notas do Editor

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