SlideShare una empresa de Scribd logo
1 de 42
Java Performance
  MythBuster
     @szarnekow




                  (c) itemis
Micro-Benchmarking

✦   Fictional Test of a Small Code-Snippet
✦   Compare Functionally Equivalent
    Implementations
✦   Seek for Arguments in the “Java is Slow”
    Battle
Disclaimer
Disclaimer
More Disclaimer


Don’t do this at home.
(even though it’s fun)
#1: Final Variables Are
        Faster

int computeSmth(final int a) {

 final int result = a * a * a;

 return result;
}
In C++, everytime someone
writes ">> 3" instead of "/ 8",
 I bet the compiler is like,
"OH DAMN! I would have
  never thought of that!"
                    (@jonshiring)
#2: String + String
       is Slow!
        "a" + "b"
            vs.

new StringBuilder("a")
 .append("b")
 .toString();
public class Sample {
   static String s = "a" + "b";
 }

$javap -c Sample
public class Sample {
   static String s = "a" + "b";
 }

$javap -c Sample
Compiled from "Sample.java"
public class Sample extends java.lang.Object{
static java.lang.String s;

static {};
  Code:
    0:! dc! #10; //String ab
      l
    2:! utstatic! #12; //Field s:Ljava/lang/String;
      p
    5:! eturn
      r
...
static String b = "b";
static String s = "a" + b;
static String b = "b";
   static String s = "a" + b;




5:!
  !    new! #14; //class StringBuilder
8:!
  !    dup
9:!
  !    ldc! #16; //String a
11:!   invokespecial! #18; //StringBuilder."<init>"
14:!   getstatic! #12; //Field b
17:!   invokevirtual! #22; //StringBuilder.append
20:!   invokevirtual! #26; //StringBuilder.toString
#3: {Objects,
Exceptions, Things} Are
      Too Slow!
Caliper
Micro-Benchmarking done right.
Caliper
Micro-Benchmarking done right.

         ✦   Warm-Up, Trails, Params
Caliper
Micro-Benchmarking done right.

         ✦   Warm-Up, Trails, Params
         ✦   Forked JVM per Trial
Caliper
Micro-Benchmarking done right.

         ✦   Warm-Up, Trails, Params
         ✦   Forked JVM per Trial
         ✦   Pretty Results
Caliper
Micro-Benchmarking done right.

         ✦   Warm-Up, Trails, Params
         ✦   Forked JVM per Trial
         ✦   Pretty Results
         ✦   Avoid “Heisenbenchmark”
List as Queue
List as Queue
The Art of Adding Numbers
   int sum() {
   
 int result = 0;
   
 for (int i = 0; i < a; i++) {
   
 
 for (int j = 0; j < b; j++) {
   
 
 
 result = result + j;
   
 
 }
   
 }
   
 return result;
   }
The Art of Adding Numbers
 ✦   Plain Imperative: Nested Loops
 ✦   Extracted Methods (addAll, add)
 ✦   Parameter Objects (AddParam, AddResult)
 ✦   Strategies (addAll(strategy)
 ✦   Fields (this.result = this.a + this.b)
 ✦   Control Flow By Exception (throw result)
Show Me The Numbers
   (a = 25000 / b = 25000)
Show Me The Numbers
   (a = 25000 / b = 25000)
Show Me The Numbers
   (a = 25000 / b = 25000)
Show Me The Numbers
   (a = 25000 / b = 25000)
Diagnose
          Some Useful VM Args
$java -server -Xmx...
 -XX:+UnlockDiagnosticVMOptions
 -XX:+PrintCompilation
 -XX:+PrintInlining
 ObjectOrientedAdder 25000 25000
More VM Args
         -XX:CompileCommand
$java -server -Xmx...
 -XX:+UnlockDiagnosticVMOptions
 -XX:+PrintCompilation
 -XX:+PrintInlining
 '-XX:CompileCommand=print,*ObjectOrientedAdder.sum*'
 ObjectOrientedAdder 25000 25000
-XX:+PrintInlining

ObjectOrientedAdder::sum (27 bytes)
@ 9 ObjectOrientedAdder::addAll (39 bytes) inline (hot)
  @ 13 AddParam::<init> (15 bytes) inline (hot)
    @ 1 java.lang.Object::<init> (1 bytes) inline (hot)
  @ 19 ObjectOrientedAdder::add (17 bytes) inline (hot)
    @ 5 AddParam::getA (5 bytes) inline (hot)
    @ 9 AddParam::getB (5 bytes) inline (hot)
    @ 13 AddResult::<init> (10 bytes) inline (hot)
      @ 1 java.lang.Object::<init> (1 byte) inline(hot)
  @ 22 AddResult::getResult (5 bytes) inline (hot)
Optimization Strategies

✦   Inlining
Optimization Strategies

✦   Inlining
✦   Intrinsics
Optimization Strategies

✦   Inlining
✦   Intrinsics
✦   Escape Analysis
Optimization Strategies

✦   Inlining
✦   Intrinsics
✦   Escape Analysis
✦   Loop Unrolling
Optimization Strategies

✦   Inlining
✦   Intrinsics
✦   Escape Analysis
✦   Loop Unrolling
✦   Lock Fusion and Lock Elision
Optimization Strategies

✦   Inlining
✦   Intrinsics
✦   Escape Analysis
✦   Loop Unrolling
✦   Lock Fusion and Lock Elision
✦   Many More ...
... As of Oct 2009
compiler tactics                           flow-sensitive rewrites                global code shaping
delayed compilation                        conditional constant propagation      inlining (graph integration)
tiered compilation                         dominating test detection             global code motion
on-stack replacement                       flow-carried type narrowing            heat-based code layout
delayed reoptimization                     dead code elimination                 switch balancing
program dependence graph representation                                          throw inlining
static single assignment representation    language-specific techniques
                                           class hierarchy analysis              control flow graph transformation
speculative (profile-based) techniques      devirtualization                      local code scheduling
optimistic nullness assertions             symbolic constant propagation         local code bundling
optimistic type assertions                 autobox elimination                   delay slot filling
optimistic type strengthening              escape analysis                       graph-coloring register allocation
optimistic array length strengthening      lock elision                          linear scan register allocation
untaken branch pruning                     lock fusion                           live range splitting
optimistic N-morphic inlining              de-reflection                          copy coalescing
branch frequency prediction                                                      constant splitting
call frequency prediction                  memory and placement transformation   copy removal
                                           expression hoisting                   address mode matching
proof-based techniques                     expression sinking                    instruction peepholing
exact type inference                       redundant store elimination           DFA-based code generator
memory value inference                     adjacent store fusion
memory value tracking                      card-mark elimination
constant folding                           merge-point splitting
reassociation
operator strength reduction                loop transformations
null check elimination                     loop unrolling
type test strength reduction               loop peeling
type test elimination                      safepoint elimination
algebraic simplification                    iteration range splitting
common subexpression elimination           range check elimination
integer range typing                       loop vectorization
Should I ...
Always Use Objects, then?
Should I ...
Always Use Objects, then?
Other Things ...
Some Advice
✦   [..] Write Readable and Clear Code. [..]
    (David Keenan)
✦   [..] slavishly follow a principle of simple, clear
    coding that avoids clever optimizations [..]
    (Caliper FAQ)
✦   Performance advice has a short shelf-life
    (B. Goetz)
Credits: I’m thankful to Arno Haase, who allowed to
         highjack the title of his great session at
         JAX 2012 which inspired me for this talk.

Más contenido relacionado

La actualidad más candente

Java tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry LevelJava tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry LevelRamrao Desai
 
Programming in Scala: Notes
Programming in Scala: NotesProgramming in Scala: Notes
Programming in Scala: NotesRoberto Casadei
 
Oop2011 actor presentation_stal
Oop2011 actor presentation_stalOop2011 actor presentation_stal
Oop2011 actor presentation_stalMichael Stal
 
Qcon2011 functions rockpresentation_f_sharp
Qcon2011 functions rockpresentation_f_sharpQcon2011 functions rockpresentation_f_sharp
Qcon2011 functions rockpresentation_f_sharpMichael Stal
 
The JavaScript Programming Language
The JavaScript Programming LanguageThe JavaScript Programming Language
The JavaScript Programming LanguageRaghavan Mohan
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side JavascriptJulie Iskander
 
DISE - Windows Based Application Development in C#
DISE - Windows Based Application Development in C#DISE - Windows Based Application Development in C#
DISE - Windows Based Application Development in C#Rasan Samarasinghe
 
Ti1220 Lecture 2: Names, Bindings, and Scopes
Ti1220 Lecture 2: Names, Bindings, and ScopesTi1220 Lecture 2: Names, Bindings, and Scopes
Ti1220 Lecture 2: Names, Bindings, and ScopesEelco Visser
 
Variables: names, bindings, type, scope
Variables: names, bindings, type, scopeVariables: names, bindings, type, scope
Variables: names, bindings, type, scopesuthi
 
2 kotlin vs. java: what java has that kotlin does not
2  kotlin vs. java: what java has that kotlin does not2  kotlin vs. java: what java has that kotlin does not
2 kotlin vs. java: what java has that kotlin does notSergey Bandysik
 
Ruby For Java Programmers
Ruby For Java ProgrammersRuby For Java Programmers
Ruby For Java ProgrammersMike Bowler
 
1 kotlin vs. java: some java issues addressed in kotlin
1  kotlin vs. java: some java issues addressed in kotlin1  kotlin vs. java: some java issues addressed in kotlin
1 kotlin vs. java: some java issues addressed in kotlinSergey Bandysik
 
Introduction to Functional Programming with Scala
Introduction to Functional Programming with ScalaIntroduction to Functional Programming with Scala
Introduction to Functional Programming with Scalapramode_ce
 

La actualidad más candente (19)

Java tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry LevelJava tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry Level
 
Programming in Scala: Notes
Programming in Scala: NotesProgramming in Scala: Notes
Programming in Scala: Notes
 
Oop2011 actor presentation_stal
Oop2011 actor presentation_stalOop2011 actor presentation_stal
Oop2011 actor presentation_stal
 
Qcon2011 functions rockpresentation_f_sharp
Qcon2011 functions rockpresentation_f_sharpQcon2011 functions rockpresentation_f_sharp
Qcon2011 functions rockpresentation_f_sharp
 
The JavaScript Programming Language
The JavaScript Programming LanguageThe JavaScript Programming Language
The JavaScript Programming Language
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
 
DISE - Windows Based Application Development in C#
DISE - Windows Based Application Development in C#DISE - Windows Based Application Development in C#
DISE - Windows Based Application Development in C#
 
Ti1220 Lecture 2: Names, Bindings, and Scopes
Ti1220 Lecture 2: Names, Bindings, and ScopesTi1220 Lecture 2: Names, Bindings, and Scopes
Ti1220 Lecture 2: Names, Bindings, and Scopes
 
Variables: names, bindings, type, scope
Variables: names, bindings, type, scopeVariables: names, bindings, type, scope
Variables: names, bindings, type, scope
 
Clean coding-practices
Clean coding-practicesClean coding-practices
Clean coding-practices
 
The Style of C++ 11
The Style of C++ 11The Style of C++ 11
The Style of C++ 11
 
java training faridabad
java training faridabadjava training faridabad
java training faridabad
 
2 kotlin vs. java: what java has that kotlin does not
2  kotlin vs. java: what java has that kotlin does not2  kotlin vs. java: what java has that kotlin does not
2 kotlin vs. java: what java has that kotlin does not
 
Ruby For Java Programmers
Ruby For Java ProgrammersRuby For Java Programmers
Ruby For Java Programmers
 
Scala fundamentals
Scala fundamentalsScala fundamentals
Scala fundamentals
 
About Python
About PythonAbout Python
About Python
 
1 kotlin vs. java: some java issues addressed in kotlin
1  kotlin vs. java: some java issues addressed in kotlin1  kotlin vs. java: some java issues addressed in kotlin
1 kotlin vs. java: some java issues addressed in kotlin
 
Introduction to Functional Programming with Scala
Introduction to Functional Programming with ScalaIntroduction to Functional Programming with Scala
Introduction to Functional Programming with Scala
 
Java Tutorials
Java Tutorials Java Tutorials
Java Tutorials
 

Similar a Java Performance MythBusters

Hidden Truths in Dead Software Paths
Hidden Truths in Dead Software PathsHidden Truths in Dead Software Paths
Hidden Truths in Dead Software PathsBen Hermann
 
Basics of Javascript
Basics of JavascriptBasics of Javascript
Basics of JavascriptUniverse41
 
javascript teach
javascript teachjavascript teach
javascript teachguest3732fa
 
JSBootcamp_White
JSBootcamp_WhiteJSBootcamp_White
JSBootcamp_Whiteguest3732fa
 
Functional Java 8 - Introduction
Functional Java 8 - IntroductionFunctional Java 8 - Introduction
Functional Java 8 - IntroductionŁukasz Biały
 
Code lifecycle in the jvm - TopConf Linz
Code lifecycle in the jvm - TopConf LinzCode lifecycle in the jvm - TopConf Linz
Code lifecycle in the jvm - TopConf LinzIvan Krylov
 
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
 
"JS: the right way" by Mykyta Semenistyi
"JS: the right way" by Mykyta Semenistyi"JS: the right way" by Mykyta Semenistyi
"JS: the right way" by Mykyta SemenistyiBinary Studio
 
Graal in GraalVM - A New JIT Compiler
Graal in GraalVM - A New JIT CompilerGraal in GraalVM - A New JIT Compiler
Graal in GraalVM - A New JIT CompilerKoichi Sakata
 
Haskell for data science
Haskell for data scienceHaskell for data science
Haskell for data scienceJohn Cant
 
Specialized Compiler for Hash Cracking
Specialized Compiler for Hash CrackingSpecialized Compiler for Hash Cracking
Specialized Compiler for Hash CrackingPositive Hack Days
 
Building a SIMD Supported Vectorized Native Engine for Spark SQL
Building a SIMD Supported Vectorized Native Engine for Spark SQLBuilding a SIMD Supported Vectorized Native Engine for Spark SQL
Building a SIMD Supported Vectorized Native Engine for Spark SQLDatabricks
 
RailswayCon 2010 - Dynamic Language VMs
RailswayCon 2010 - Dynamic Language VMsRailswayCon 2010 - Dynamic Language VMs
RailswayCon 2010 - Dynamic Language VMsLourens Naudé
 
Quick Intro To JRuby
Quick Intro To JRubyQuick Intro To JRuby
Quick Intro To JRubyFrederic Jean
 
Inspecting Block Closures To Generate Shaders for GPU Execution
Inspecting Block Closures To Generate Shaders for GPU ExecutionInspecting Block Closures To Generate Shaders for GPU Execution
Inspecting Block Closures To Generate Shaders for GPU ExecutionESUG
 
Swift Micro-services and AWS Technologies
Swift Micro-services and AWS TechnologiesSwift Micro-services and AWS Technologies
Swift Micro-services and AWS TechnologiesSimonPilkington8
 
Implementing a JavaScript Engine
Implementing a JavaScript EngineImplementing a JavaScript Engine
Implementing a JavaScript EngineKris Mok
 
Productive Debugging
Productive DebuggingProductive Debugging
Productive DebuggingiThink
 

Similar a Java Performance MythBusters (20)

Hidden Truths in Dead Software Paths
Hidden Truths in Dead Software PathsHidden Truths in Dead Software Paths
Hidden Truths in Dead Software Paths
 
Basics of Javascript
Basics of JavascriptBasics of Javascript
Basics of Javascript
 
javascript teach
javascript teachjavascript teach
javascript teach
 
JSBootcamp_White
JSBootcamp_WhiteJSBootcamp_White
JSBootcamp_White
 
Functional Java 8 - Introduction
Functional Java 8 - IntroductionFunctional Java 8 - Introduction
Functional Java 8 - Introduction
 
Code lifecycle in the jvm - TopConf Linz
Code lifecycle in the jvm - TopConf LinzCode lifecycle in the jvm - TopConf Linz
Code lifecycle in the jvm - TopConf Linz
 
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
 
"JS: the right way" by Mykyta Semenistyi
"JS: the right way" by Mykyta Semenistyi"JS: the right way" by Mykyta Semenistyi
"JS: the right way" by Mykyta Semenistyi
 
Graal in GraalVM - A New JIT Compiler
Graal in GraalVM - A New JIT CompilerGraal in GraalVM - A New JIT Compiler
Graal in GraalVM - A New JIT Compiler
 
Haskell for data science
Haskell for data scienceHaskell for data science
Haskell for data science
 
Specialized Compiler for Hash Cracking
Specialized Compiler for Hash CrackingSpecialized Compiler for Hash Cracking
Specialized Compiler for Hash Cracking
 
Building a SIMD Supported Vectorized Native Engine for Spark SQL
Building a SIMD Supported Vectorized Native Engine for Spark SQLBuilding a SIMD Supported Vectorized Native Engine for Spark SQL
Building a SIMD Supported Vectorized Native Engine for Spark SQL
 
RailswayCon 2010 - Dynamic Language VMs
RailswayCon 2010 - Dynamic Language VMsRailswayCon 2010 - Dynamic Language VMs
RailswayCon 2010 - Dynamic Language VMs
 
Quick Intro To JRuby
Quick Intro To JRubyQuick Intro To JRuby
Quick Intro To JRuby
 
Inspecting Block Closures To Generate Shaders for GPU Execution
Inspecting Block Closures To Generate Shaders for GPU ExecutionInspecting Block Closures To Generate Shaders for GPU Execution
Inspecting Block Closures To Generate Shaders for GPU Execution
 
Swift Micro-services and AWS Technologies
Swift Micro-services and AWS TechnologiesSwift Micro-services and AWS Technologies
Swift Micro-services and AWS Technologies
 
Intro to J Ruby
Intro to J RubyIntro to J Ruby
Intro to J Ruby
 
Implementing a JavaScript Engine
Implementing a JavaScript EngineImplementing a JavaScript Engine
Implementing a JavaScript Engine
 
Productive Debugging
Productive DebuggingProductive Debugging
Productive Debugging
 
Headless Js Testing
Headless Js TestingHeadless Js Testing
Headless Js Testing
 

Más de Sebastian Zarnekow

Extending the Xbase Typesystem
Extending the Xbase TypesystemExtending the Xbase Typesystem
Extending the Xbase TypesystemSebastian Zarnekow
 
Building a Python IDE with Xtext
Building a Python IDE with XtextBuilding a Python IDE with Xtext
Building a Python IDE with XtextSebastian Zarnekow
 
Xtend - A Language Made for Java Developers
Xtend - A Language Made for Java DevelopersXtend - A Language Made for Java Developers
Xtend - A Language Made for Java DevelopersSebastian Zarnekow
 
MDSD with Eclipse @ JUG Hamburg
MDSD with Eclipse @ JUG HamburgMDSD with Eclipse @ JUG Hamburg
MDSD with Eclipse @ JUG HamburgSebastian Zarnekow
 
Eclipse DemoCamp in Paris: Language Development with Xtext
Eclipse DemoCamp in Paris: Language Development with XtextEclipse DemoCamp in Paris: Language Development with Xtext
Eclipse DemoCamp in Paris: Language Development with XtextSebastian Zarnekow
 
Textual Modeling Framework Xtext
Textual Modeling Framework XtextTextual Modeling Framework Xtext
Textual Modeling Framework XtextSebastian Zarnekow
 

Más de Sebastian Zarnekow (8)

Scoping Tips and Tricks
Scoping Tips and TricksScoping Tips and Tricks
Scoping Tips and Tricks
 
Extending the Xbase Typesystem
Extending the Xbase TypesystemExtending the Xbase Typesystem
Extending the Xbase Typesystem
 
Building a Python IDE with Xtext
Building a Python IDE with XtextBuilding a Python IDE with Xtext
Building a Python IDE with Xtext
 
Xtext Best Practices
Xtext Best PracticesXtext Best Practices
Xtext Best Practices
 
Xtend - A Language Made for Java Developers
Xtend - A Language Made for Java DevelopersXtend - A Language Made for Java Developers
Xtend - A Language Made for Java Developers
 
MDSD with Eclipse @ JUG Hamburg
MDSD with Eclipse @ JUG HamburgMDSD with Eclipse @ JUG Hamburg
MDSD with Eclipse @ JUG Hamburg
 
Eclipse DemoCamp in Paris: Language Development with Xtext
Eclipse DemoCamp in Paris: Language Development with XtextEclipse DemoCamp in Paris: Language Development with Xtext
Eclipse DemoCamp in Paris: Language Development with Xtext
 
Textual Modeling Framework Xtext
Textual Modeling Framework XtextTextual Modeling Framework Xtext
Textual Modeling Framework Xtext
 

Último

Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
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
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
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
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
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
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
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
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 

Último (20)

Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
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
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
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...
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
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
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
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
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 

Java Performance MythBusters

  • 1. Java Performance MythBuster @szarnekow (c) itemis
  • 2. Micro-Benchmarking ✦ Fictional Test of a Small Code-Snippet ✦ Compare Functionally Equivalent Implementations ✦ Seek for Arguments in the “Java is Slow” Battle
  • 5. More Disclaimer Don’t do this at home. (even though it’s fun)
  • 6. #1: Final Variables Are Faster int computeSmth(final int a) { final int result = a * a * a; return result; }
  • 7. In C++, everytime someone writes ">> 3" instead of "/ 8", I bet the compiler is like, "OH DAMN! I would have never thought of that!" (@jonshiring)
  • 8. #2: String + String is Slow! "a" + "b" vs. new StringBuilder("a") .append("b") .toString();
  • 9. public class Sample { static String s = "a" + "b"; } $javap -c Sample
  • 10. public class Sample { static String s = "a" + "b"; } $javap -c Sample Compiled from "Sample.java" public class Sample extends java.lang.Object{ static java.lang.String s; static {}; Code: 0:! dc! #10; //String ab l 2:! utstatic! #12; //Field s:Ljava/lang/String; p 5:! eturn r ...
  • 11. static String b = "b"; static String s = "a" + b;
  • 12. static String b = "b"; static String s = "a" + b; 5:! ! new! #14; //class StringBuilder 8:! ! dup 9:! ! ldc! #16; //String a 11:! invokespecial! #18; //StringBuilder."<init>" 14:! getstatic! #12; //Field b 17:! invokevirtual! #22; //StringBuilder.append 20:! invokevirtual! #26; //StringBuilder.toString
  • 15. Caliper Micro-Benchmarking done right. ✦ Warm-Up, Trails, Params
  • 16. Caliper Micro-Benchmarking done right. ✦ Warm-Up, Trails, Params ✦ Forked JVM per Trial
  • 17. Caliper Micro-Benchmarking done right. ✦ Warm-Up, Trails, Params ✦ Forked JVM per Trial ✦ Pretty Results
  • 18. Caliper Micro-Benchmarking done right. ✦ Warm-Up, Trails, Params ✦ Forked JVM per Trial ✦ Pretty Results ✦ Avoid “Heisenbenchmark”
  • 21. The Art of Adding Numbers int sum() { int result = 0; for (int i = 0; i < a; i++) { for (int j = 0; j < b; j++) { result = result + j; } } return result; }
  • 22. The Art of Adding Numbers ✦ Plain Imperative: Nested Loops ✦ Extracted Methods (addAll, add) ✦ Parameter Objects (AddParam, AddResult) ✦ Strategies (addAll(strategy) ✦ Fields (this.result = this.a + this.b) ✦ Control Flow By Exception (throw result)
  • 23. Show Me The Numbers (a = 25000 / b = 25000)
  • 24. Show Me The Numbers (a = 25000 / b = 25000)
  • 25. Show Me The Numbers (a = 25000 / b = 25000)
  • 26. Show Me The Numbers (a = 25000 / b = 25000)
  • 27. Diagnose Some Useful VM Args $java -server -Xmx... -XX:+UnlockDiagnosticVMOptions -XX:+PrintCompilation -XX:+PrintInlining ObjectOrientedAdder 25000 25000
  • 28. More VM Args -XX:CompileCommand $java -server -Xmx... -XX:+UnlockDiagnosticVMOptions -XX:+PrintCompilation -XX:+PrintInlining '-XX:CompileCommand=print,*ObjectOrientedAdder.sum*' ObjectOrientedAdder 25000 25000
  • 29.
  • 30. -XX:+PrintInlining ObjectOrientedAdder::sum (27 bytes) @ 9 ObjectOrientedAdder::addAll (39 bytes) inline (hot) @ 13 AddParam::<init> (15 bytes) inline (hot) @ 1 java.lang.Object::<init> (1 bytes) inline (hot) @ 19 ObjectOrientedAdder::add (17 bytes) inline (hot) @ 5 AddParam::getA (5 bytes) inline (hot) @ 9 AddParam::getB (5 bytes) inline (hot) @ 13 AddResult::<init> (10 bytes) inline (hot) @ 1 java.lang.Object::<init> (1 byte) inline(hot) @ 22 AddResult::getResult (5 bytes) inline (hot)
  • 32. Optimization Strategies ✦ Inlining ✦ Intrinsics
  • 33. Optimization Strategies ✦ Inlining ✦ Intrinsics ✦ Escape Analysis
  • 34. Optimization Strategies ✦ Inlining ✦ Intrinsics ✦ Escape Analysis ✦ Loop Unrolling
  • 35. Optimization Strategies ✦ Inlining ✦ Intrinsics ✦ Escape Analysis ✦ Loop Unrolling ✦ Lock Fusion and Lock Elision
  • 36. Optimization Strategies ✦ Inlining ✦ Intrinsics ✦ Escape Analysis ✦ Loop Unrolling ✦ Lock Fusion and Lock Elision ✦ Many More ...
  • 37. ... As of Oct 2009 compiler tactics flow-sensitive rewrites global code shaping delayed compilation conditional constant propagation inlining (graph integration) tiered compilation dominating test detection global code motion on-stack replacement flow-carried type narrowing heat-based code layout delayed reoptimization dead code elimination switch balancing program dependence graph representation throw inlining static single assignment representation language-specific techniques class hierarchy analysis control flow graph transformation speculative (profile-based) techniques devirtualization local code scheduling optimistic nullness assertions symbolic constant propagation local code bundling optimistic type assertions autobox elimination delay slot filling optimistic type strengthening escape analysis graph-coloring register allocation optimistic array length strengthening lock elision linear scan register allocation untaken branch pruning lock fusion live range splitting optimistic N-morphic inlining de-reflection copy coalescing branch frequency prediction constant splitting call frequency prediction memory and placement transformation copy removal expression hoisting address mode matching proof-based techniques expression sinking instruction peepholing exact type inference redundant store elimination DFA-based code generator memory value inference adjacent store fusion memory value tracking card-mark elimination constant folding merge-point splitting reassociation operator strength reduction loop transformations null check elimination loop unrolling type test strength reduction loop peeling type test elimination safepoint elimination algebraic simplification iteration range splitting common subexpression elimination range check elimination integer range typing loop vectorization
  • 38. Should I ... Always Use Objects, then?
  • 39. Should I ... Always Use Objects, then?
  • 41. Some Advice ✦ [..] Write Readable and Clear Code. [..] (David Keenan) ✦ [..] slavishly follow a principle of simple, clear coding that avoids clever optimizations [..] (Caliper FAQ) ✦ Performance advice has a short shelf-life (B. Goetz)
  • 42. Credits: I’m thankful to Arno Haase, who allowed to highjack the title of his great session at JAX 2012 which inspired me for this talk.

Notas del editor

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n
  32. \n
  33. \n
  34. \n
  35. \n
  36. \n
  37. \n
  38. \n