SlideShare uma empresa Scribd logo
1 de 32
HotSpot
● The brain in which our Java and Scala juices
flow.
● Its execution speed and efficiency is
nearing that of native compiled code.
● At its core: The JIT compiler.
So... The JIT compiler?
● Information is gathered at runtime.
○ Which paths in the code are traveled often?
○ Which methods are called the most, or, where are
the hot spots?
So... The JIT compiler?
● Once enough information about a hot
method is collected...
○ The compiler kicks in.
○ Compiles the bytecode into a lean and efficient
native version of itself.
○ May re-compile later due to over-optimism.
Some standard optimizations
● Simple method inlining.
● Dead code removal.
● Native math ops instead of library calls.
● Invariant hoisting.
Some are extra awesome!
Divide and conquer
How many times have you used the following
pattern?
StringBuilder sb = new StringBuilder("Ingredients: ");
for (int i = 0; i < ingredients.length; i++) {
if (i > 0) {
sb.append(", ");
}
sb.append(ingredients[i]);
}
return sb.toString();
Divide and conquer
...or perhaps this one?
boolean nemoFound = false;
for (int i = 0; i < fish.length; i++) {
String curFish = fish[i];
if (!nemoFound) {
if (curFish.equals("Nemo")) {
System.out.println("Nemo! There you are!");
nemoFound = true;
continue;
}
}
if (nemoFound) {
System.out.println("We already found Nemo!");
} else {
System.out.println("We still haven't found Nemo :(");
}
}
Divide and conquer
● Both loops do one thing for a while,
● Then another thing from a certain point on.
● The compiler can spot these patterns.
○ Split the loops into cases.
○ “Peel” several iterations.
Divide and conquer
● The condition: if (i > 0)
○ false once,
○ true thereafter.
○ Peel one iteration!
StringBuilder sb = new StringBuilder("Ingredients: ");
for (int i = 0; i < ingredients.length; i++) {
if (i > 0) {
sb.append(", ");
}
sb.append(ingredients[i]);
}
return sb.toString();
Divide and conquer
...will compile as if it were written like so:
StringBuilder sb = new StringBuilder("Ingredients: ");
if (ingredients.length > 0) {
sb.append(ingredients[0]);
for (int i = 1; i < ingredients.length; i++) {
sb.append(", ");
sb.append(ingredients[i]);
}
}
return sb.toString();
First iteration
All other iterations
Living on the edge
● Null checks are bread-and-butter.
● Sometimes null is a valid value:
○ Missing values
○ Error indication
● Sometimes we check just to be on the safe
side.
Living on the edge
Some checks may be practically redundant.
If your code behaves well, the assertion may
never fail.
public static String l33tify(String phrase) {
if (phrase == null) {
throw new IllegalArgumentException("Null bad!");
}
return phrase.replace('e', '3');
}
Living on the edge
● Code runs many, many times.
● The assertion never fails.
● The JIT compiler is optimistic.
...assumes the check is unnecessary!
Living on the edge
The compiler may drop the check altogether,
and compile it as if it were written like so:
public static String l33tify(String phrase) {
if (phrase == null) {
throw new IllegalArgumentException("Null bad!");
}
return phrase.replace('e', '3');
}
Living on the edge
Wait...
What if that happy-path assumption
eventually proves to be wrong?
Living on the edge
● The JVM is now executing native code.
○ A null reference would not result in a fuzzy
NullPointerException.
...but rather in a real, harsh memory
access violation.
Living on the edge
● The JVM intercepts the SIGSEGV (and recovers)
● Follows-up with a de-optimization.
...Method is recompiled, this time with the
null check in place.
Virtual insanity
The JIT compiler has dynamic runtime data on
which it can rely when making decisions.
Virtual insanity
Method inlining:
Step 1: Take invoked method.
Step 2: Take invoker method.
Step 3: Embed former in latter.
Virtual insanity
Method inlining:
○ Useful when trying to avoid costly invocations.
○ Tricky when dealing with dynamic dispatch.
Virtual insanity
public class Main {
public static void perform(Song s) {
s.sing();
}
}
public interface Song {
public void sing();
}
Virtual insanity
public class GangnamStyle implements Song {
@Override
public void sing() {
println("Oppan gangnam style!");
}
}
public class Baby implements Song {
@Override
public void sing() {
println("And I was like baby, baby, baby, oh");
}
}
public class BohemianRhapsody implements Song {
@Override
public void sing() {
println("Thunderbolt and lightning, very very frightening me");
}
}
Virtual insanity
● perform might run millions of times.
● Each time, sing is invoked.
This is a co$tly dynamic dispatch!
Virtual insanity
Inlining polymorphic calls is not so simple...
...in a static compiler.
Virtual insanity
The JIT compiler is dynamic.
Take advantage of runtime information!
Virtual insanity
The JVM might decide, according to the
statistics it gathered, that 95% of the
invocations target an instance of
GangnamStyle.
Virtual insanity
The compiler can perform an optimistic
optimization:
Eliminate the virtual calls to sing.
...or most of them anyway.
Virtual insanity
Optimized compiled code will behave like so:
public static void perform(Song s) {
if (s fastnativeinstanceof GangnamStyle) {
println("Oppan gangnam style!");
} else {
s.sing();
}
}
Can I help?
● The JIT compiler is built to optimize:
○ Straightforward, simple code.
○ Common patterns.
○ No nonsense.
Can I help?
The best way to help your compiler is to not
try so hard to help it.
Just write your code as you otherwise would!
JVM Performance Magic Tricks

Mais conteúdo relacionado

Mais procurados

Groovy AST Transformations
Groovy AST TransformationsGroovy AST Transformations
Groovy AST Transformationshendersk
 
Asynchronous Programming with Kotlin
Asynchronous Programming with KotlinAsynchronous Programming with Kotlin
Asynchronous Programming with KotlinJ On The Beach
 
Memory management in C++
Memory management in C++Memory management in C++
Memory management in C++Ilio Catallo
 
Introduction to Rust language programming
Introduction to Rust language programmingIntroduction to Rust language programming
Introduction to Rust language programmingRodolfo Finochietti
 
What’s new in Kotlin?
What’s new in Kotlin?What’s new in Kotlin?
What’s new in Kotlin?Squareboat
 

Mais procurados (6)

Php training in chandigarh
Php  training in chandigarhPhp  training in chandigarh
Php training in chandigarh
 
Groovy AST Transformations
Groovy AST TransformationsGroovy AST Transformations
Groovy AST Transformations
 
Asynchronous Programming with Kotlin
Asynchronous Programming with KotlinAsynchronous Programming with Kotlin
Asynchronous Programming with Kotlin
 
Memory management in C++
Memory management in C++Memory management in C++
Memory management in C++
 
Introduction to Rust language programming
Introduction to Rust language programmingIntroduction to Rust language programming
Introduction to Rust language programming
 
What’s new in Kotlin?
What’s new in Kotlin?What’s new in Kotlin?
What’s new in Kotlin?
 

Destaque

Freddy Fusion | Smoke Magic Secret
Freddy Fusion | Smoke Magic Secret Freddy Fusion | Smoke Magic Secret
Freddy Fusion | Smoke Magic Secret Freddy Fusion
 
Magic Tricks 110 Page Ebook
Magic Tricks 110 Page EbookMagic Tricks 110 Page Ebook
Magic Tricks 110 Page Ebookpanthep
 
Game of Performance: A Song of JIT and GC
Game of Performance: A Song of JIT and GCGame of Performance: A Song of JIT and GC
Game of Performance: A Song of JIT and GCMonica Beckwith
 
110 Amazing Magic Tricks
110 Amazing Magic Tricks110 Amazing Magic Tricks
110 Amazing Magic TricksAayush Mudgal
 
Java Jit. Compilation and optimization by Andrey Kovalenko
Java Jit. Compilation and optimization by Andrey KovalenkoJava Jit. Compilation and optimization by Andrey Kovalenko
Java Jit. Compilation and optimization by Andrey KovalenkoValeriia Maliarenko
 
Tips for Effective Presentations
Tips for Effective PresentationsTips for Effective Presentations
Tips for Effective PresentationsK Covintree
 

Destaque (6)

Freddy Fusion | Smoke Magic Secret
Freddy Fusion | Smoke Magic Secret Freddy Fusion | Smoke Magic Secret
Freddy Fusion | Smoke Magic Secret
 
Magic Tricks 110 Page Ebook
Magic Tricks 110 Page EbookMagic Tricks 110 Page Ebook
Magic Tricks 110 Page Ebook
 
Game of Performance: A Song of JIT and GC
Game of Performance: A Song of JIT and GCGame of Performance: A Song of JIT and GC
Game of Performance: A Song of JIT and GC
 
110 Amazing Magic Tricks
110 Amazing Magic Tricks110 Amazing Magic Tricks
110 Amazing Magic Tricks
 
Java Jit. Compilation and optimization by Andrey Kovalenko
Java Jit. Compilation and optimization by Andrey KovalenkoJava Jit. Compilation and optimization by Andrey Kovalenko
Java Jit. Compilation and optimization by Andrey Kovalenko
 
Tips for Effective Presentations
Tips for Effective PresentationsTips for Effective Presentations
Tips for Effective Presentations
 

Semelhante a JVM Performance Magic Tricks

How do you create a programming language for the JVM?
How do you create a programming language for the JVM?How do you create a programming language for the JVM?
How do you create a programming language for the JVM?Federico Tomassetti
 
Building reusable libraries
Building reusable librariesBuilding reusable libraries
Building reusable librariesFelix Morgner
 
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...Charles Nutter
 
Java best practices
Java best practicesJava best practices
Java best practicesRay Toal
 
Giorgio zoppi cpp11concurrency
Giorgio zoppi cpp11concurrencyGiorgio zoppi cpp11concurrency
Giorgio zoppi cpp11concurrencyGiorgio Zoppi
 
Validating Big Data Jobs—Stopping Failures Before Production on Apache Spark...
 Validating Big Data Jobs—Stopping Failures Before Production on Apache Spark... Validating Big Data Jobs—Stopping Failures Before Production on Apache Spark...
Validating Big Data Jobs—Stopping Failures Before Production on Apache Spark...Databricks
 
How much performance can you get out of Javascript? - Massimiliano Mantione -...
How much performance can you get out of Javascript? - Massimiliano Mantione -...How much performance can you get out of Javascript? - Massimiliano Mantione -...
How much performance can you get out of Javascript? - Massimiliano Mantione -...Codemotion
 
JavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for DummiesJavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for DummiesCharles Nutter
 
Fuzzing: The New Unit Testing
Fuzzing: The New Unit TestingFuzzing: The New Unit Testing
Fuzzing: The New Unit TestingDmitry Vyukov
 
AOT-compilation of JavaScript with V8
AOT-compilation of JavaScript with V8AOT-compilation of JavaScript with V8
AOT-compilation of JavaScript with V8Phil Eaton
 
stacks and queues class 12 in c++
stacks and  queues class 12 in c++stacks and  queues class 12 in c++
stacks and queues class 12 in c++Khushal Mehta
 
Of complicacy of programming, or won't C# save us?
Of complicacy of programming, or won't C# save us?Of complicacy of programming, or won't C# save us?
Of complicacy of programming, or won't C# save us?PVS-Studio
 
2. overview of c#
2. overview of c#2. overview of c#
2. overview of c#Rohit Rao
 
Intro to Arduino Programming.pdf
Intro to Arduino Programming.pdfIntro to Arduino Programming.pdf
Intro to Arduino Programming.pdfHimanshuDon1
 

Semelhante a JVM Performance Magic Tricks (20)

How do you create a programming language for the JVM?
How do you create a programming language for the JVM?How do you create a programming language for the JVM?
How do you create a programming language for the JVM?
 
Java Performance Tuning
Java Performance TuningJava Performance Tuning
Java Performance Tuning
 
Building reusable libraries
Building reusable librariesBuilding reusable libraries
Building reusable libraries
 
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...
 
Pyramid of-developer-skills
Pyramid of-developer-skillsPyramid of-developer-skills
Pyramid of-developer-skills
 
Java best practices
Java best practicesJava best practices
Java best practices
 
Giorgio zoppi cpp11concurrency
Giorgio zoppi cpp11concurrencyGiorgio zoppi cpp11concurrency
Giorgio zoppi cpp11concurrency
 
Validating Big Data Jobs—Stopping Failures Before Production on Apache Spark...
 Validating Big Data Jobs—Stopping Failures Before Production on Apache Spark... Validating Big Data Jobs—Stopping Failures Before Production on Apache Spark...
Validating Big Data Jobs—Stopping Failures Before Production on Apache Spark...
 
How much performance can you get out of Javascript? - Massimiliano Mantione -...
How much performance can you get out of Javascript? - Massimiliano Mantione -...How much performance can you get out of Javascript? - Massimiliano Mantione -...
How much performance can you get out of Javascript? - Massimiliano Mantione -...
 
JavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for DummiesJavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for Dummies
 
Stop that!
Stop that!Stop that!
Stop that!
 
Android ndk
Android ndkAndroid ndk
Android ndk
 
Fuzzing: The New Unit Testing
Fuzzing: The New Unit TestingFuzzing: The New Unit Testing
Fuzzing: The New Unit Testing
 
AOT-compilation of JavaScript with V8
AOT-compilation of JavaScript with V8AOT-compilation of JavaScript with V8
AOT-compilation of JavaScript with V8
 
Java For Automation
Java   For AutomationJava   For Automation
Java For Automation
 
stacks and queues class 12 in c++
stacks and  queues class 12 in c++stacks and  queues class 12 in c++
stacks and queues class 12 in c++
 
Of complicacy of programming, or won't C# save us?
Of complicacy of programming, or won't C# save us?Of complicacy of programming, or won't C# save us?
Of complicacy of programming, or won't C# save us?
 
2. overview of c#
2. overview of c#2. overview of c#
2. overview of c#
 
Why learn Internals?
Why learn Internals?Why learn Internals?
Why learn Internals?
 
Intro to Arduino Programming.pdf
Intro to Arduino Programming.pdfIntro to Arduino Programming.pdf
Intro to Arduino Programming.pdf
 

Mais de Takipi

Advanced Production Debugging
Advanced Production DebuggingAdvanced Production Debugging
Advanced Production DebuggingTakipi
 
AppDynamics VS New Relic – The Complete Guide
AppDynamics VS New Relic – The Complete GuideAppDynamics VS New Relic – The Complete Guide
AppDynamics VS New Relic – The Complete GuideTakipi
 
The Dark Side Of Lambda Expressions in Java 8
The Dark Side Of Lambda Expressions in Java 8The Dark Side Of Lambda Expressions in Java 8
The Dark Side Of Lambda Expressions in Java 8Takipi
 
Java 9 – The Ultimate Feature List
Java 9 – The Ultimate Feature ListJava 9 – The Ultimate Feature List
Java 9 – The Ultimate Feature ListTakipi
 
7 New Tools Java Developers Should Know
7 New Tools Java Developers Should Know7 New Tools Java Developers Should Know
7 New Tools Java Developers Should KnowTakipi
 
5 Coding Hacks to Reduce GC Overhead
5 Coding Hacks to Reduce GC Overhead5 Coding Hacks to Reduce GC Overhead
5 Coding Hacks to Reduce GC OverheadTakipi
 
JVM bytecode - The secret language behind Java and Scala
JVM bytecode - The secret language behind Java and ScalaJVM bytecode - The secret language behind Java and Scala
JVM bytecode - The secret language behind Java and ScalaTakipi
 

Mais de Takipi (7)

Advanced Production Debugging
Advanced Production DebuggingAdvanced Production Debugging
Advanced Production Debugging
 
AppDynamics VS New Relic – The Complete Guide
AppDynamics VS New Relic – The Complete GuideAppDynamics VS New Relic – The Complete Guide
AppDynamics VS New Relic – The Complete Guide
 
The Dark Side Of Lambda Expressions in Java 8
The Dark Side Of Lambda Expressions in Java 8The Dark Side Of Lambda Expressions in Java 8
The Dark Side Of Lambda Expressions in Java 8
 
Java 9 – The Ultimate Feature List
Java 9 – The Ultimate Feature ListJava 9 – The Ultimate Feature List
Java 9 – The Ultimate Feature List
 
7 New Tools Java Developers Should Know
7 New Tools Java Developers Should Know7 New Tools Java Developers Should Know
7 New Tools Java Developers Should Know
 
5 Coding Hacks to Reduce GC Overhead
5 Coding Hacks to Reduce GC Overhead5 Coding Hacks to Reduce GC Overhead
5 Coding Hacks to Reduce GC Overhead
 
JVM bytecode - The secret language behind Java and Scala
JVM bytecode - The secret language behind Java and ScalaJVM bytecode - The secret language behind Java and Scala
JVM bytecode - The secret language behind Java and Scala
 

Último

Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...apidays
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusZilliz
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024The Digital Insurer
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 

Último (20)

Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 

JVM Performance Magic Tricks

  • 1.
  • 2. HotSpot ● The brain in which our Java and Scala juices flow. ● Its execution speed and efficiency is nearing that of native compiled code. ● At its core: The JIT compiler.
  • 3. So... The JIT compiler? ● Information is gathered at runtime. ○ Which paths in the code are traveled often? ○ Which methods are called the most, or, where are the hot spots?
  • 4. So... The JIT compiler? ● Once enough information about a hot method is collected... ○ The compiler kicks in. ○ Compiles the bytecode into a lean and efficient native version of itself. ○ May re-compile later due to over-optimism.
  • 5. Some standard optimizations ● Simple method inlining. ● Dead code removal. ● Native math ops instead of library calls. ● Invariant hoisting.
  • 6. Some are extra awesome!
  • 7. Divide and conquer How many times have you used the following pattern? StringBuilder sb = new StringBuilder("Ingredients: "); for (int i = 0; i < ingredients.length; i++) { if (i > 0) { sb.append(", "); } sb.append(ingredients[i]); } return sb.toString();
  • 8. Divide and conquer ...or perhaps this one? boolean nemoFound = false; for (int i = 0; i < fish.length; i++) { String curFish = fish[i]; if (!nemoFound) { if (curFish.equals("Nemo")) { System.out.println("Nemo! There you are!"); nemoFound = true; continue; } } if (nemoFound) { System.out.println("We already found Nemo!"); } else { System.out.println("We still haven't found Nemo :("); } }
  • 9. Divide and conquer ● Both loops do one thing for a while, ● Then another thing from a certain point on. ● The compiler can spot these patterns. ○ Split the loops into cases. ○ “Peel” several iterations.
  • 10. Divide and conquer ● The condition: if (i > 0) ○ false once, ○ true thereafter. ○ Peel one iteration! StringBuilder sb = new StringBuilder("Ingredients: "); for (int i = 0; i < ingredients.length; i++) { if (i > 0) { sb.append(", "); } sb.append(ingredients[i]); } return sb.toString();
  • 11. Divide and conquer ...will compile as if it were written like so: StringBuilder sb = new StringBuilder("Ingredients: "); if (ingredients.length > 0) { sb.append(ingredients[0]); for (int i = 1; i < ingredients.length; i++) { sb.append(", "); sb.append(ingredients[i]); } } return sb.toString(); First iteration All other iterations
  • 12. Living on the edge ● Null checks are bread-and-butter. ● Sometimes null is a valid value: ○ Missing values ○ Error indication ● Sometimes we check just to be on the safe side.
  • 13. Living on the edge Some checks may be practically redundant. If your code behaves well, the assertion may never fail. public static String l33tify(String phrase) { if (phrase == null) { throw new IllegalArgumentException("Null bad!"); } return phrase.replace('e', '3'); }
  • 14. Living on the edge ● Code runs many, many times. ● The assertion never fails. ● The JIT compiler is optimistic. ...assumes the check is unnecessary!
  • 15. Living on the edge The compiler may drop the check altogether, and compile it as if it were written like so: public static String l33tify(String phrase) { if (phrase == null) { throw new IllegalArgumentException("Null bad!"); } return phrase.replace('e', '3'); }
  • 16. Living on the edge Wait... What if that happy-path assumption eventually proves to be wrong?
  • 17. Living on the edge ● The JVM is now executing native code. ○ A null reference would not result in a fuzzy NullPointerException. ...but rather in a real, harsh memory access violation.
  • 18. Living on the edge ● The JVM intercepts the SIGSEGV (and recovers) ● Follows-up with a de-optimization. ...Method is recompiled, this time with the null check in place.
  • 19. Virtual insanity The JIT compiler has dynamic runtime data on which it can rely when making decisions.
  • 20. Virtual insanity Method inlining: Step 1: Take invoked method. Step 2: Take invoker method. Step 3: Embed former in latter.
  • 21. Virtual insanity Method inlining: ○ Useful when trying to avoid costly invocations. ○ Tricky when dealing with dynamic dispatch.
  • 22. Virtual insanity public class Main { public static void perform(Song s) { s.sing(); } } public interface Song { public void sing(); }
  • 23. Virtual insanity public class GangnamStyle implements Song { @Override public void sing() { println("Oppan gangnam style!"); } } public class Baby implements Song { @Override public void sing() { println("And I was like baby, baby, baby, oh"); } } public class BohemianRhapsody implements Song { @Override public void sing() { println("Thunderbolt and lightning, very very frightening me"); } }
  • 24. Virtual insanity ● perform might run millions of times. ● Each time, sing is invoked. This is a co$tly dynamic dispatch!
  • 25. Virtual insanity Inlining polymorphic calls is not so simple... ...in a static compiler.
  • 26. Virtual insanity The JIT compiler is dynamic. Take advantage of runtime information!
  • 27. Virtual insanity The JVM might decide, according to the statistics it gathered, that 95% of the invocations target an instance of GangnamStyle.
  • 28. Virtual insanity The compiler can perform an optimistic optimization: Eliminate the virtual calls to sing. ...or most of them anyway.
  • 29. Virtual insanity Optimized compiled code will behave like so: public static void perform(Song s) { if (s fastnativeinstanceof GangnamStyle) { println("Oppan gangnam style!"); } else { s.sing(); } }
  • 30. Can I help? ● The JIT compiler is built to optimize: ○ Straightforward, simple code. ○ Common patterns. ○ No nonsense.
  • 31. Can I help? The best way to help your compiler is to not try so hard to help it. Just write your code as you otherwise would!