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

Weitere ähnliche Inhalte

Was ist angesagt?

Sga internals
Sga internalsSga internals
Sga internals
sergkosko
 

Was ist angesagt? (20)

Oracle RAC Internals - The Cache Fusion Edition
Oracle RAC Internals - The Cache Fusion EditionOracle RAC Internals - The Cache Fusion Edition
Oracle RAC Internals - The Cache Fusion Edition
 
PostgreSQLのリカバリ超入門(もしくはWAL、CHECKPOINT、オンラインバックアップの仕組み)
PostgreSQLのリカバリ超入門(もしくはWAL、CHECKPOINT、オンラインバックアップの仕組み)PostgreSQLのリカバリ超入門(もしくはWAL、CHECKPOINT、オンラインバックアップの仕組み)
PostgreSQLのリカバリ超入門(もしくはWAL、CHECKPOINT、オンラインバックアップの仕組み)
 
YugaByte DB Internals - Storage Engine and Transactions
YugaByte DB Internals - Storage Engine and Transactions YugaByte DB Internals - Storage Engine and Transactions
YugaByte DB Internals - Storage Engine and Transactions
 
Understanding oracle rac internals part 2 - slides
Understanding oracle rac internals   part 2 - slidesUnderstanding oracle rac internals   part 2 - slides
Understanding oracle rac internals part 2 - slides
 
CloudNativePGを動かしてみた! ~PostgreSQL on Kubernetes~(第34回PostgreSQLアンカンファレンス@オンライ...
CloudNativePGを動かしてみた! ~PostgreSQL on Kubernetes~(第34回PostgreSQLアンカンファレンス@オンライ...CloudNativePGを動かしてみた! ~PostgreSQL on Kubernetes~(第34回PostgreSQLアンカンファレンス@オンライ...
CloudNativePGを動かしてみた! ~PostgreSQL on Kubernetes~(第34回PostgreSQLアンカンファレンス@オンライ...
 
分散システムについて語らせてくれ
分散システムについて語らせてくれ分散システムについて語らせてくれ
分散システムについて語らせてくれ
 
ORACLE 12C DATA GUARD: FAR SYNC, REAL-TIME CASCADE STANDBY AND OTHER GOODIES
ORACLE 12C DATA GUARD: FAR SYNC, REAL-TIME CASCADE STANDBY AND OTHER GOODIESORACLE 12C DATA GUARD: FAR SYNC, REAL-TIME CASCADE STANDBY AND OTHER GOODIES
ORACLE 12C DATA GUARD: FAR SYNC, REAL-TIME CASCADE STANDBY AND OTHER GOODIES
 
Low Level CPU Performance Profiling Examples
Low Level CPU Performance Profiling ExamplesLow Level CPU Performance Profiling Examples
Low Level CPU Performance Profiling Examples
 
Sga internals
Sga internalsSga internals
Sga internals
 
並行実行制御の最適化手法
並行実行制御の最適化手法並行実行制御の最適化手法
並行実行制御の最適化手法
 
MyRocks Deep Dive
MyRocks Deep DiveMyRocks Deep Dive
MyRocks Deep Dive
 
The Google Chubby lock service for loosely-coupled distributed systems
The Google Chubby lock service for loosely-coupled distributed systemsThe Google Chubby lock service for loosely-coupled distributed systems
The Google Chubby lock service for loosely-coupled distributed systems
 
トランザクション処理可能な分散DB 「YugabyteDB」入門(Open Source Conference 2022 Online/Fukuoka 発...
トランザクション処理可能な分散DB 「YugabyteDB」入門(Open Source Conference 2022 Online/Fukuoka 発...トランザクション処理可能な分散DB 「YugabyteDB」入門(Open Source Conference 2022 Online/Fukuoka 発...
トランザクション処理可能な分散DB 「YugabyteDB」入門(Open Source Conference 2022 Online/Fukuoka 発...
 
Isolation Level について
Isolation Level についてIsolation Level について
Isolation Level について
 
PostgreSQL 14 モニタリング新機能紹介(PostgreSQL カンファレンス #24、2021/06/08)
PostgreSQL 14 モニタリング新機能紹介(PostgreSQL カンファレンス #24、2021/06/08)PostgreSQL 14 モニタリング新機能紹介(PostgreSQL カンファレンス #24、2021/06/08)
PostgreSQL 14 モニタリング新機能紹介(PostgreSQL カンファレンス #24、2021/06/08)
 
Percona XtraDB Cluster ( Ensure high Availability )
Percona XtraDB Cluster ( Ensure high Availability )Percona XtraDB Cluster ( Ensure high Availability )
Percona XtraDB Cluster ( Ensure high Availability )
 
Devsの常識、DBAは非常識
Devsの常識、DBAは非常識Devsの常識、DBAは非常識
Devsの常識、DBAは非常識
 
HashiCorpのNomadを使ったコンテナのスケジューリング手法
HashiCorpのNomadを使ったコンテナのスケジューリング手法HashiCorpのNomadを使ったコンテナのスケジューリング手法
HashiCorpのNomadを使ったコンテナのスケジューリング手法
 
Optimizing MariaDB for maximum performance
Optimizing MariaDB for maximum performanceOptimizing MariaDB for maximum performance
Optimizing MariaDB for maximum performance
 
Log Structured Merge Tree
Log Structured Merge TreeLog Structured Merge Tree
Log Structured Merge Tree
 

Andere mochten auch

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
 

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

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

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

Kürzlich hochgeladen

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Kürzlich hochgeladen (20)

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
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
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...
 
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...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
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
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
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
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
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...
 
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...
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
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
 
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
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 

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