SlideShare ist ein Scribd-Unternehmen logo
1 von 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

Weitere ähnliche Inhalte

Was ist angesagt?

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
 

Was ist angesagt? (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?
 

Andere mochten auch

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
 

Andere mochten auch (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
 

Ähnlich wie 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
 

Ähnlich wie 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
 

Mehr von 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
 

Mehr von 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
 

Kürzlich hochgeladen

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
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbuapidays
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Zilliz
 
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
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
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
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
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
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
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
 
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
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelDeepika Singh
 
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
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 

Kürzlich hochgeladen (20)

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
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
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
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
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...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
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
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
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
 
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
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
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...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 

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!