SlideShare une entreprise Scribd logo
1  sur  36
SCALA PROFILING
                             (for Java developers)




                                                     Filippo Pacifici


mercoledì 23 maggio 12
Who am I
                    • Filippo Pacifici
                     • Twitter: OddId_
                     • mail: filippo.pacifici@gmail.com
                     • Blog: http://outofmemoryblog.blogspot.com
                    • One of the 9M devs thinking Java is not so bad
                     • recently started looking at Scala
mercoledì 23 maggio 12
What’s this all about?
                    • Apply Java profiling methods to Scala
                         programs
                         • How do we deal with performance in
                           Java?
                         • Is it the same in Scala?
                    • How do we optimize a JVM for Scala
                         applications?


mercoledì 23 maggio 12
Java profiling 101



mercoledì 23 maggio 12
Java profiling 101

                    • Goals:
                     • troubleshoot performance problems
                     • estimate application performance
                     • estimate application scalability

mercoledì 23 maggio 12
Java profiling 101
                    • Ehi, I use Scala, why should I care about Java
                         profiling?
                         • Scala compiled in byte code and runs in a
                           JVM
                         • We can profile a Scala application as it
                           was Java
                         • We can use the same tools
                         • I am not aware of alternatives
mercoledì 23 maggio 12
Java methods profiling
 •      Tracks methods invocations

       •      Runtime instrumentation

       •      Time analysis




mercoledì 23 maggio 12
Java memory profiling
       •      Dumps heap content

             •     Browse objects in the heap

             •     Memory usage analysis




mercoledì 23 maggio 12
Profiling tools
                    • Method profiling
                     • Java Visual VM (embedded in JDK)
                     • Yourkit, Dynatrace, etc.
                    • Memory profiling
                     • Eclipse MAT (www.eclipse.org/
                           mat)
                         • Yourkit, Dynatrace, etc.
mercoledì 23 maggio 12
Back to Scala...

                    • We won’t find Scala specific constructs
                     • Need to know how Scala is translated
                           into bytecode
                    • Goals:
                     • Identify methods generated by Scala
                           compilers
                         • Characterize Scala data structures in
                           memory
mercoledì 23 maggio 12
Scala Functions



mercoledì 23 maggio 12
Short discouraging
                         comparative demo



mercoledì 23 maggio 12
Scala functions vs byte code

                    • Classic functions converted in methods
                    • First class function do not exist in Java
                     • Anonymous classes extending
                           scala.runtime.AbstractFunction
                         • apply method to execute.

mercoledì 23 maggio 12
AbstractFunction
      •     AbstractFunction2

            •     takes 2 input parameters

      •     One apply method per
            combination of input and
            output types

            •     example apply.mcFID

                 •       F= returns float

                 •       I takes one Int

                 •       D takes one Double
mercoledì 23 maggio 12
AbstractFunction
                    • Find the call in the profile:


                • anonfun => instance of the anonymous class
                • main$1 => first anonymous class defined in
                         main method


mercoledì 23 maggio 12
Functions in the heap

                    • Each instance of AbstractFunction present
                         in the heap
                         • Very small impact
                         • Stateless


mercoledì 23 maggio 12
Where do we use them?
                    • Our program did not contain any anonymous
                         function, right?
                    • AbstractFunction used:
                     • For first class functions
                     • For closures
                     • For partially applied functions
                     • To manage for loops blocks
                     • To manage filter logic in for loops
mercoledì 23 maggio 12
Performance impact
                    • Is this a performance impact?
                     • Scala compiler performs optimizations:
                        • Same anonymous functions reused
                           (avoid multiple instantiations)
                         • Anonymous functions doing the same
                           thing are shared
                         • Attention to partially applied:
                          • New function created.
mercoledì 23 maggio 12
Some examples



mercoledì 23 maggio 12
Scala data structures
                             (Collections in heap dump)




mercoledì 23 maggio 12
Scala Lists
                    • A Scala view:
                     • Linked lists (single link)
                     • abstract class List + two case classes: ::
                         and Nil




mercoledì 23 maggio 12
Scala Lists
                    • A byte code view:
                     • Case classes become inner classes:
                       • :: becomes $colon$colon
                       • Nil becomes Nil



mercoledì 23 maggio 12
Scala Lists
                • Heads and elements have the same type




mercoledì 23 maggio 12
Scala Lists

                    • What about mutable lists?
                     • ListBuffer
                       • Wrapper on a Linked List
                       • Keeps an additional reference to the
                          last element: last0



mercoledì 23 maggio 12
Scala Sets
                    • Immutable sets
                     • scala.collection.immutable.Set
                     • Case classes for different sizes
                     • HashSet over 5 elements


mercoledì 23 maggio 12
Scala Maps

                    • Immutable:
                     • small number of elements:
                           scala.collections.immutable.Map$MapN
                         • N = number of elements
                         • over 5 elements:
                           scala.collection.immutable.HashMap
                    • Mutable: scala.collection.mutable.HashMap
mercoledì 23 maggio 12
Map and Sets examples



mercoledì 23 maggio 12
Primitive types boxing



mercoledì 23 maggio 12
Primitive types and
                               generics
                    • Type parameters cannot be primitive in
                         generic types.
                         • Scala systematically boxes and unboxes
                           them to Object
                         • scala.runtime.BoxesRunTime methods


mercoledì 23 maggio 12
Basic tuning tips



mercoledì 23 maggio 12
Exploit tail recursion
                    • Long recursion
                     • Long stack
                     • Performance impact on stack size
                    • Scala compiler recognizes tail recursion
                     • Recursive call must be the last operation
                           of the method
                         • Scala transforms it into iterative form

mercoledì 23 maggio 12
Can’t exploit tail
                               recursion?
                    • If (and only if) you run out of stack space
                         (frequent java.lang.StackOverflowError):
                         • -Xss JVM option sets stack size
                         • example: -Xss2048k
                         • Normally limited at OS level
                         • Each thread statically allocates stack size:
                          • pay attention
mercoledì 23 maggio 12
Memory structure
                    • Optimize for small, short lived objects
                     • Anonymous functions:
                       • small
                       • frequently instantiated
                     • Use a big young space
                       • GC is fast and frequent
                       • Objects do not get promoted
mercoledì 23 maggio 12
Memory structure

                    • What about the perm gen?
                     • Anonymous classes reused
                     • No insane usage of proxies
                     • No specific issues

mercoledì 23 maggio 12
Which GC should I use?
                    • Depends on your application requirements
                     • The same consideration done for Java
                         still hold
                         • Need throughput : parallel GC
                         • Need response time : CMS
                         • You are brave : G1
mercoledì 23 maggio 12
Questions?



mercoledì 23 maggio 12

Contenu connexe

Tendances

Concurrency Patterns with MongoDB
Concurrency Patterns with MongoDBConcurrency Patterns with MongoDB
Concurrency Patterns with MongoDB
Yann Cluchey
 
Etsy Activity Feeds Architecture
Etsy Activity Feeds ArchitectureEtsy Activity Feeds Architecture
Etsy Activity Feeds Architecture
Dan McKinley
 
Apache Cassandra Multi-Datacenter Essentials (Julien Anguenot, iLand Internet...
Apache Cassandra Multi-Datacenter Essentials (Julien Anguenot, iLand Internet...Apache Cassandra Multi-Datacenter Essentials (Julien Anguenot, iLand Internet...
Apache Cassandra Multi-Datacenter Essentials (Julien Anguenot, iLand Internet...
DataStax
 

Tendances (14)

Peer to peer data management
Peer to peer data managementPeer to peer data management
Peer to peer data management
 
Netflix Keystone - How Netflix Handles Data Streams up to 11M Events/Sec
Netflix Keystone - How Netflix Handles Data Streams up to 11M Events/SecNetflix Keystone - How Netflix Handles Data Streams up to 11M Events/Sec
Netflix Keystone - How Netflix Handles Data Streams up to 11M Events/Sec
 
8. mutual exclusion in Distributed Operating Systems
8. mutual exclusion in Distributed Operating Systems8. mutual exclusion in Distributed Operating Systems
8. mutual exclusion in Distributed Operating Systems
 
Mac protocols for ad hoc wireless networks
Mac protocols for ad hoc wireless networks Mac protocols for ad hoc wireless networks
Mac protocols for ad hoc wireless networks
 
How Apache Kafka® Works
How Apache Kafka® WorksHow Apache Kafka® Works
How Apache Kafka® Works
 
Flexible and Real-Time Stream Processing with Apache Flink
Flexible and Real-Time Stream Processing with Apache FlinkFlexible and Real-Time Stream Processing with Apache Flink
Flexible and Real-Time Stream Processing with Apache Flink
 
Cache coherence ppt
Cache coherence pptCache coherence ppt
Cache coherence ppt
 
Building Microservices with Apache Kafka
Building Microservices with Apache KafkaBuilding Microservices with Apache Kafka
Building Microservices with Apache Kafka
 
Concurrency Patterns with MongoDB
Concurrency Patterns with MongoDBConcurrency Patterns with MongoDB
Concurrency Patterns with MongoDB
 
Concurrency & Parallel Programming
Concurrency & Parallel ProgrammingConcurrency & Parallel Programming
Concurrency & Parallel Programming
 
Etsy Activity Feeds Architecture
Etsy Activity Feeds ArchitectureEtsy Activity Feeds Architecture
Etsy Activity Feeds Architecture
 
Gorm
GormGorm
Gorm
 
Kafka at half the price with JBOD setup
Kafka at half the price with JBOD setupKafka at half the price with JBOD setup
Kafka at half the price with JBOD setup
 
Apache Cassandra Multi-Datacenter Essentials (Julien Anguenot, iLand Internet...
Apache Cassandra Multi-Datacenter Essentials (Julien Anguenot, iLand Internet...Apache Cassandra Multi-Datacenter Essentials (Julien Anguenot, iLand Internet...
Apache Cassandra Multi-Datacenter Essentials (Julien Anguenot, iLand Internet...
 

En vedette

Procedure Typing for Scala
Procedure Typing for ScalaProcedure Typing for Scala
Procedure Typing for Scala
akuklev
 
Scalaのコンパイルを3倍速くした話
Scalaのコンパイルを3倍速くした話Scalaのコンパイルを3倍速くした話
Scalaのコンパイルを3倍速くした話
tod esking
 
Colaboración y Negocios Web 20
Colaboración y Negocios Web 20Colaboración y Negocios Web 20
Colaboración y Negocios Web 20
Emprende Futuro
 
Top 20 TV Online PC-Movil por Garritz Media Online
Top 20 TV Online PC-Movil por Garritz Media OnlineTop 20 TV Online PC-Movil por Garritz Media Online
Top 20 TV Online PC-Movil por Garritz Media Online
IAB México
 
Comunicado Numero 1 CIMI
Comunicado Numero 1 CIMIComunicado Numero 1 CIMI
Comunicado Numero 1 CIMI
Desarrollo Sena
 
Teatro romano de Zaragoza. Cristina Valero (2º bach.)
Teatro romano de Zaragoza. Cristina Valero (2º bach.)Teatro romano de Zaragoza. Cristina Valero (2º bach.)
Teatro romano de Zaragoza. Cristina Valero (2º bach.)
humanidadescolapias
 

En vedette (20)

Scala in practice
Scala in practiceScala in practice
Scala in practice
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009
 
Metaprogramming in Scala 2.10, Eugene Burmako,
Metaprogramming  in Scala 2.10, Eugene Burmako, Metaprogramming  in Scala 2.10, Eugene Burmako,
Metaprogramming in Scala 2.10, Eugene Burmako,
 
Scala test
Scala testScala test
Scala test
 
Scalding: Twitter's Scala DSL for Hadoop/Cascading
Scalding: Twitter's Scala DSL for Hadoop/CascadingScalding: Twitter's Scala DSL for Hadoop/Cascading
Scalding: Twitter's Scala DSL for Hadoop/Cascading
 
Procedure Typing for Scala
Procedure Typing for ScalaProcedure Typing for Scala
Procedure Typing for Scala
 
RESTful API using scalaz (3)
RESTful API using scalaz (3)RESTful API using scalaz (3)
RESTful API using scalaz (3)
 
Scalaのコンパイルを3倍速くした話
Scalaのコンパイルを3倍速くした話Scalaのコンパイルを3倍速くした話
Scalaのコンパイルを3倍速くした話
 
Colaboración y Negocios Web 20
Colaboración y Negocios Web 20Colaboración y Negocios Web 20
Colaboración y Negocios Web 20
 
Creative that cracks the code applied to indian market - Group 6
Creative that cracks the code applied to indian market - Group 6Creative that cracks the code applied to indian market - Group 6
Creative that cracks the code applied to indian market - Group 6
 
Fyronic seminar-software factorymeeting-sls
Fyronic seminar-software factorymeeting-slsFyronic seminar-software factorymeeting-sls
Fyronic seminar-software factorymeeting-sls
 
Present redes lvg
Present redes lvgPresent redes lvg
Present redes lvg
 
Despierta Papa Despierta
Despierta Papa DespiertaDespierta Papa Despierta
Despierta Papa Despierta
 
Top 20 TV Online PC-Movil por Garritz Media Online
Top 20 TV Online PC-Movil por Garritz Media OnlineTop 20 TV Online PC-Movil por Garritz Media Online
Top 20 TV Online PC-Movil por Garritz Media Online
 
Felicitación navidad 2013
Felicitación navidad 2013Felicitación navidad 2013
Felicitación navidad 2013
 
Comunicado Numero 1 CIMI
Comunicado Numero 1 CIMIComunicado Numero 1 CIMI
Comunicado Numero 1 CIMI
 
Teatro romano de Zaragoza. Cristina Valero (2º bach.)
Teatro romano de Zaragoza. Cristina Valero (2º bach.)Teatro romano de Zaragoza. Cristina Valero (2º bach.)
Teatro romano de Zaragoza. Cristina Valero (2º bach.)
 
LA CRÓNICA 636
LA CRÓNICA 636LA CRÓNICA 636
LA CRÓNICA 636
 
México 1968 orígenes de la transición Soledad Loaeza
México 1968 orígenes de la transición Soledad LoaezaMéxico 1968 orígenes de la transición Soledad Loaeza
México 1968 orígenes de la transición Soledad Loaeza
 
Building TV apps with Chromecast
Building TV apps with ChromecastBuilding TV apps with Chromecast
Building TV apps with Chromecast
 

Similaire à Scala profiling

Polyglot Plugin Programming
Polyglot Plugin ProgrammingPolyglot Plugin Programming
Polyglot Plugin Programming
Atlassian
 
Writing DSL's in Scala
Writing DSL's in ScalaWriting DSL's in Scala
Writing DSL's in Scala
Abhijit Sharma
 
An Introduction to Scala
An Introduction to ScalaAn Introduction to Scala
An Introduction to Scala
Brent Lemons
 

Similaire à Scala profiling (20)

Polyglot and functional (Devoxx Nov/2011)
Polyglot and functional (Devoxx Nov/2011)Polyglot and functional (Devoxx Nov/2011)
Polyglot and functional (Devoxx Nov/2011)
 
Scala adoption by enterprises
Scala adoption by enterprisesScala adoption by enterprises
Scala adoption by enterprises
 
Polyglot Plugin Programming
Polyglot Plugin ProgrammingPolyglot Plugin Programming
Polyglot Plugin Programming
 
Scalaマクロ入門 bizr20170217
Scalaマクロ入門 bizr20170217 Scalaマクロ入門 bizr20170217
Scalaマクロ入門 bizr20170217
 
Writing DSL's in Scala
Writing DSL's in ScalaWriting DSL's in Scala
Writing DSL's in Scala
 
Project Lambda, JSR 335
Project Lambda, JSR 335Project Lambda, JSR 335
Project Lambda, JSR 335
 
Introduction to Java 7 (Devoxx Nov/2011)
Introduction to Java 7 (Devoxx Nov/2011)Introduction to Java 7 (Devoxx Nov/2011)
Introduction to Java 7 (Devoxx Nov/2011)
 
Polyglot and Functional Programming (OSCON 2012)
Polyglot and Functional Programming (OSCON 2012)Polyglot and Functional Programming (OSCON 2012)
Polyglot and Functional Programming (OSCON 2012)
 
An Introduction to Scala
An Introduction to ScalaAn Introduction to Scala
An Introduction to Scala
 
Using Scala for building DSLs
Using Scala for building DSLsUsing Scala for building DSLs
Using Scala for building DSLs
 
Java Closures
Java ClosuresJava Closures
Java Closures
 
My sql tutorial-oscon-2012
My sql tutorial-oscon-2012My sql tutorial-oscon-2012
My sql tutorial-oscon-2012
 
Rails Performance Tuning
Rails Performance TuningRails Performance Tuning
Rails Performance Tuning
 
Scala Past, Present & Future
Scala Past, Present & FutureScala Past, Present & Future
Scala Past, Present & Future
 
Concurrency and Multithreading Demistified - Reversim Summit 2014
Concurrency and Multithreading Demistified - Reversim Summit 2014Concurrency and Multithreading Demistified - Reversim Summit 2014
Concurrency and Multithreading Demistified - Reversim Summit 2014
 
6장 Thread Synchronization
6장 Thread Synchronization6장 Thread Synchronization
6장 Thread Synchronization
 
Experience Converting from Ruby to Scala
Experience Converting from Ruby to ScalaExperience Converting from Ruby to Scala
Experience Converting from Ruby to Scala
 
Composable Futures with Akka 2.0
Composable Futures with Akka 2.0Composable Futures with Akka 2.0
Composable Futures with Akka 2.0
 
Ruby to Scala in 9 weeks
Ruby to Scala in 9 weeksRuby to Scala in 9 weeks
Ruby to Scala in 9 weeks
 
Metaprogramming Primer (Part 1)
Metaprogramming Primer (Part 1)Metaprogramming Primer (Part 1)
Metaprogramming Primer (Part 1)
 

Dernier

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
Earley Information Science
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 

Dernier (20)

GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
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
 
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
 
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...
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
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
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
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
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
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
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
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...
 

Scala profiling

  • 1. SCALA PROFILING (for Java developers) Filippo Pacifici mercoledì 23 maggio 12
  • 2. Who am I • Filippo Pacifici • Twitter: OddId_ • mail: filippo.pacifici@gmail.com • Blog: http://outofmemoryblog.blogspot.com • One of the 9M devs thinking Java is not so bad • recently started looking at Scala mercoledì 23 maggio 12
  • 3. What’s this all about? • Apply Java profiling methods to Scala programs • How do we deal with performance in Java? • Is it the same in Scala? • How do we optimize a JVM for Scala applications? mercoledì 23 maggio 12
  • 5. Java profiling 101 • Goals: • troubleshoot performance problems • estimate application performance • estimate application scalability mercoledì 23 maggio 12
  • 6. Java profiling 101 • Ehi, I use Scala, why should I care about Java profiling? • Scala compiled in byte code and runs in a JVM • We can profile a Scala application as it was Java • We can use the same tools • I am not aware of alternatives mercoledì 23 maggio 12
  • 7. Java methods profiling • Tracks methods invocations • Runtime instrumentation • Time analysis mercoledì 23 maggio 12
  • 8. Java memory profiling • Dumps heap content • Browse objects in the heap • Memory usage analysis mercoledì 23 maggio 12
  • 9. Profiling tools • Method profiling • Java Visual VM (embedded in JDK) • Yourkit, Dynatrace, etc. • Memory profiling • Eclipse MAT (www.eclipse.org/ mat) • Yourkit, Dynatrace, etc. mercoledì 23 maggio 12
  • 10. Back to Scala... • We won’t find Scala specific constructs • Need to know how Scala is translated into bytecode • Goals: • Identify methods generated by Scala compilers • Characterize Scala data structures in memory mercoledì 23 maggio 12
  • 12. Short discouraging comparative demo mercoledì 23 maggio 12
  • 13. Scala functions vs byte code • Classic functions converted in methods • First class function do not exist in Java • Anonymous classes extending scala.runtime.AbstractFunction • apply method to execute. mercoledì 23 maggio 12
  • 14. AbstractFunction • AbstractFunction2 • takes 2 input parameters • One apply method per combination of input and output types • example apply.mcFID • F= returns float • I takes one Int • D takes one Double mercoledì 23 maggio 12
  • 15. AbstractFunction • Find the call in the profile: • anonfun => instance of the anonymous class • main$1 => first anonymous class defined in main method mercoledì 23 maggio 12
  • 16. Functions in the heap • Each instance of AbstractFunction present in the heap • Very small impact • Stateless mercoledì 23 maggio 12
  • 17. Where do we use them? • Our program did not contain any anonymous function, right? • AbstractFunction used: • For first class functions • For closures • For partially applied functions • To manage for loops blocks • To manage filter logic in for loops mercoledì 23 maggio 12
  • 18. Performance impact • Is this a performance impact? • Scala compiler performs optimizations: • Same anonymous functions reused (avoid multiple instantiations) • Anonymous functions doing the same thing are shared • Attention to partially applied: • New function created. mercoledì 23 maggio 12
  • 20. Scala data structures (Collections in heap dump) mercoledì 23 maggio 12
  • 21. Scala Lists • A Scala view: • Linked lists (single link) • abstract class List + two case classes: :: and Nil mercoledì 23 maggio 12
  • 22. Scala Lists • A byte code view: • Case classes become inner classes: • :: becomes $colon$colon • Nil becomes Nil mercoledì 23 maggio 12
  • 23. Scala Lists • Heads and elements have the same type mercoledì 23 maggio 12
  • 24. Scala Lists • What about mutable lists? • ListBuffer • Wrapper on a Linked List • Keeps an additional reference to the last element: last0 mercoledì 23 maggio 12
  • 25. Scala Sets • Immutable sets • scala.collection.immutable.Set • Case classes for different sizes • HashSet over 5 elements mercoledì 23 maggio 12
  • 26. Scala Maps • Immutable: • small number of elements: scala.collections.immutable.Map$MapN • N = number of elements • over 5 elements: scala.collection.immutable.HashMap • Mutable: scala.collection.mutable.HashMap mercoledì 23 maggio 12
  • 27. Map and Sets examples mercoledì 23 maggio 12
  • 29. Primitive types and generics • Type parameters cannot be primitive in generic types. • Scala systematically boxes and unboxes them to Object • scala.runtime.BoxesRunTime methods mercoledì 23 maggio 12
  • 31. Exploit tail recursion • Long recursion • Long stack • Performance impact on stack size • Scala compiler recognizes tail recursion • Recursive call must be the last operation of the method • Scala transforms it into iterative form mercoledì 23 maggio 12
  • 32. Can’t exploit tail recursion? • If (and only if) you run out of stack space (frequent java.lang.StackOverflowError): • -Xss JVM option sets stack size • example: -Xss2048k • Normally limited at OS level • Each thread statically allocates stack size: • pay attention mercoledì 23 maggio 12
  • 33. Memory structure • Optimize for small, short lived objects • Anonymous functions: • small • frequently instantiated • Use a big young space • GC is fast and frequent • Objects do not get promoted mercoledì 23 maggio 12
  • 34. Memory structure • What about the perm gen? • Anonymous classes reused • No insane usage of proxies • No specific issues mercoledì 23 maggio 12
  • 35. Which GC should I use? • Depends on your application requirements • The same consideration done for Java still hold • Need throughput : parallel GC • Need response time : CMS • You are brave : G1 mercoledì 23 maggio 12