SlideShare une entreprise Scribd logo
1  sur  15
Dispatch in Clojure                             Carlo Sciolla, Product Lead @ Backbase




DISPATCH IN CLOJURE | August 8, 2012 | @skuro
(ns aot
  (:gen-class))

(defn -main [& args]
  (dorun
   (map println (seq args))))


 javap -c aot.class

 A quick journey in function calling
 We all learn to divide our code in functions, and invoke them when it’s
 their time on the stage of data processing. We define units of
 computations, ready to be executed.
 DISPATCH IN CLOJURE | August 8, 2012 | @skuro
public static void main(java.lang.String[]);
[..]
   4:! invokevirtual!#66;
[..]
   26:!invokestatic!
                   #104;
   29:!invokeinterface! #108, 2;
[..]
   44:!invokespecial!#115;    (defn -main [& args]
[..]                            (dorun
                                 (map println (seq args))))

 The JVM executes our code
 We’ll leave it to the JVM to figure out which code to actually run upon
 function call. It’s not always a straightforward job, and there are several
 ways to get to the code.
 DISPATCH IN CLOJURE | August 8, 2012 | @skuro
public static void main(java.lang.String[]);
[..]
   4:! invokevirtual!#66;
[..]
   26:!invokestatic!
                   #104;
   29:!invokeinterface! #108, 2;
[..]
   44:!invokespecial!#115;
[..]

 [clojure.lang.RT] static public ISeq seq(Object coll)

 Static dispatch
 When there’s nothing to choose from, the compiler emits a static
 dispatch bytecode. All calls will always result in the same code being
 executed.
 DISPATCH IN CLOJURE | August 8, 2012 | @skuro
public static void main(java.lang.String[]);
[..]
   4:! invokevirtual!#66;
[..]
   26:!invokestatic!
                   #104;
   29:!invokeinterface! #108, 2;
[..]
   44:!invokespecial!#115;
[..]



 Dynamic dispatch
 Most often the compiler can’t figure out the proper method
 implementation to call, and the runtime will get its chance to
 dynamically dispatch the call.
 DISPATCH IN CLOJURE | August 8, 2012 | @skuro
*    dispatch by arity
*    object oriented inheritance
*    multimethods
*    custom is-a hierarchies
*    protocols




    The options at hand
    Clojure provides a rich interface to dynamic dispatch, allowing
    programmers to have control over the dispatch logic at different
    degrees to find the optimal balance on the performance trade off scale.
    DISPATCH IN CLOJURE | August 8, 2012 | @skuro
*    dispatch by arity
*    object oriented inheritance (defn sum-them
*    multimethods                  ([x y] (+ x y))
*    custom is-a hierarchies       ([x y z] (+ x y z)))
*    protocols




    The good old arity
    Being a dynamically typed language, Clojure only checks on the
    number of arguments provided in the function call to find the right
    implementation to call.
    DISPATCH IN CLOJURE | August 8, 2012 | @skuro
*    dispatch by arity           (defn stringify [x]
*    object oriented inheritance   (.toString x))
*    multimethods
*    custom is-a hierarchies     (stringify (HashMap.)) ; “{}”
*    protocols                   (stringify (HashSet.)) ; “[]”




    More than Java™
    Thanks to Clojure intimacy with Java, object inheritance is easily
    achieved. Thanks to Clojure dynamic typing, it also allows functions to
    traverse multiple inheritance trees.
    DISPATCH IN CLOJURE | August 8, 2012 | @skuro
(defn stringify*
                                                      [^HashMap x]
                                                      (.toString x))
*    dispatch by arity
*    object oriented inheritance
                                 (stringify* (HashMap.))
*    multimethods
                                 => “{}”
*    custom is-a hierarchies
                                 (stringify* (TreeMap.))
*    protocols
                                 => “{}”
                                 (stringify* (HashSet.))
                                 => ClassCastException


    Forcing virtual dispatch to improve performance
    Being a dynamic language has a number of benefits, but performance
    isn’t one of them. To avoid reflection calls needed by default by the
    dynamic dispatch you can use type hints.
    DISPATCH IN CLOJURE | August 8, 2012 | @skuro
(defn dispatch-fn
                                                      [{:keys [version]}]
*    dispatch by arity
                                                      version)
*    object oriented inheritance
*    multimethods
                                 (defmulti multi-call
*    custom is-a hierarchies
                                   dispatch-fn)
*    protocols
                                                    http://bit.ly/multi-tests



    Full power
    Multimethods allow you to define your own dispatch strategy as a plain
    Clojure function. Their limit is the sky: they perform quite bad, and your
    dispatch fn can’t be changed or extended in user code.
    DISPATCH IN CLOJURE | August 8, 2012 | @skuro
(defmethod
                                                      multi-call ::custom-type
*    dispatch by arity
                                                      [x] [...])
*    object oriented inheritance
*    multimethods
                                 (derive java.util.HashSet
*    custom is-a hierarchies
                                   ::custom-type)
*    protocols
                                                    http://bit.ly/multi-tests



    Inheritance à la carte
    Java types hierarchies defined outside your code can be “altered” by
    custom is-a? relationships created as needed. You can either use the
    default hierarchy or use make-hierarchy to restrict its scope.
    DISPATCH IN CLOJURE | August 8, 2012 | @skuro
(defprotocol Registered
                                                      (register [this]))
*    dispatch by arity
*    object oriented inheritance
                                 (extend-type String
*    multimethods
                                   Registered
*    custom is-a hierarchies
                                   (register [this] [...]))
*    protocols
                                                    http://bit.ly/proto-tests



    Inheritance à la carte
    Java types hierarchies defined outside your code can be “altered” by
    custom is-a? relationships created as needed. You can either use the
    default hierarchy or use make-hierarchy to restrict its scope.
    DISPATCH IN CLOJURE | August 8, 2012 | @skuro
*    never used when compiling pure Java
*    moves type checking at run time
*    the compiler doesn’t resolve the method
*    user code to perform the dispatch
*    eligible for JIT optimizations



    http://bit.ly/headius-invokedynamic

    Bonus track: invokedynamic
    Java7 introduced a new bytecode instruction to help JVM languages
    designers: invokedynamic. There’s a long standing discussion as which
    benefits it can provide to Clojure.
    DISPATCH IN CLOJURE | August 8, 2012 | @skuro
Q/A

DISPATCH IN CLOJURE | August 8, 2012 | @skuro
Thanks!
                                                  Amsterdam Clojurians
                Carlo Sciolla
                Product Lead




             http://skuro.tk
            @skuro
                                                http://bit.ly/amsclojure



DISPATCH IN CLOJURE | August 8, 2012 | @skuro

Contenu connexe

Tendances

JRuby @ Boulder Ruby
JRuby @ Boulder RubyJRuby @ Boulder Ruby
JRuby @ Boulder RubyNick Sieger
 
服务框架: Thrift & PasteScript
服务框架: Thrift & PasteScript服务框架: Thrift & PasteScript
服务框架: Thrift & PasteScriptQiangning Hong
 
API management with Taffy and API Blueprint
API management with Taffy and API BlueprintAPI management with Taffy and API Blueprint
API management with Taffy and API BlueprintKai Koenig
 
Interceptors: Into the Core of Pedestal
Interceptors: Into the Core of PedestalInterceptors: Into the Core of Pedestal
Interceptors: Into the Core of PedestalKent Ohashi
 
Symfony2 Service Container: Inject me, my friend
Symfony2 Service Container: Inject me, my friendSymfony2 Service Container: Inject me, my friend
Symfony2 Service Container: Inject me, my friendKirill Chebunin
 
ES2015 (ES6) Overview
ES2015 (ES6) OverviewES2015 (ES6) Overview
ES2015 (ES6) Overviewhesher
 
Php unit the-mostunknownparts
Php unit the-mostunknownpartsPhp unit the-mostunknownparts
Php unit the-mostunknownpartsBastian Feder
 
Blocks & GCD
Blocks & GCDBlocks & GCD
Blocks & GCDrsebbe
 
Objective-C Blocks and Grand Central Dispatch
Objective-C Blocks and Grand Central DispatchObjective-C Blocks and Grand Central Dispatch
Objective-C Blocks and Grand Central DispatchMatteo Battaglio
 
The Beauty and the Beast
The Beauty and the BeastThe Beauty and the Beast
The Beauty and the BeastBastian Feder
 
Py conkr 20150829_docker-python
Py conkr 20150829_docker-pythonPy conkr 20150829_docker-python
Py conkr 20150829_docker-pythonEric Ahn
 
Introduction to Nodejs
Introduction to NodejsIntroduction to Nodejs
Introduction to NodejsGabriele Lana
 
Replacing "exec" with a type and provider: Return manifests to a declarative ...
Replacing "exec" with a type and provider: Return manifests to a declarative ...Replacing "exec" with a type and provider: Return manifests to a declarative ...
Replacing "exec" with a type and provider: Return manifests to a declarative ...Puppet
 
Scaling Symfony2 apps with RabbitMQ - Symfony UK Meetup
Scaling Symfony2 apps with RabbitMQ - Symfony UK MeetupScaling Symfony2 apps with RabbitMQ - Symfony UK Meetup
Scaling Symfony2 apps with RabbitMQ - Symfony UK MeetupKacper Gunia
 
Stanford Hackathon - Puppet Modules
Stanford Hackathon - Puppet ModulesStanford Hackathon - Puppet Modules
Stanford Hackathon - Puppet ModulesPuppet
 
Explaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to ComeExplaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to ComeCory Forsyth
 

Tendances (19)

JRuby @ Boulder Ruby
JRuby @ Boulder RubyJRuby @ Boulder Ruby
JRuby @ Boulder Ruby
 
服务框架: Thrift & PasteScript
服务框架: Thrift & PasteScript服务框架: Thrift & PasteScript
服务框架: Thrift & PasteScript
 
API management with Taffy and API Blueprint
API management with Taffy and API BlueprintAPI management with Taffy and API Blueprint
API management with Taffy and API Blueprint
 
Interceptors: Into the Core of Pedestal
Interceptors: Into the Core of PedestalInterceptors: Into the Core of Pedestal
Interceptors: Into the Core of Pedestal
 
Symfony2 Service Container: Inject me, my friend
Symfony2 Service Container: Inject me, my friendSymfony2 Service Container: Inject me, my friend
Symfony2 Service Container: Inject me, my friend
 
Puppet @ Seat
Puppet @ SeatPuppet @ Seat
Puppet @ Seat
 
High Performance tDiary
High Performance tDiaryHigh Performance tDiary
High Performance tDiary
 
ES2015 (ES6) Overview
ES2015 (ES6) OverviewES2015 (ES6) Overview
ES2015 (ES6) Overview
 
Php unit the-mostunknownparts
Php unit the-mostunknownpartsPhp unit the-mostunknownparts
Php unit the-mostunknownparts
 
Blocks & GCD
Blocks & GCDBlocks & GCD
Blocks & GCD
 
Objective-C Blocks and Grand Central Dispatch
Objective-C Blocks and Grand Central DispatchObjective-C Blocks and Grand Central Dispatch
Objective-C Blocks and Grand Central Dispatch
 
The Beauty and the Beast
The Beauty and the BeastThe Beauty and the Beast
The Beauty and the Beast
 
Py conkr 20150829_docker-python
Py conkr 20150829_docker-pythonPy conkr 20150829_docker-python
Py conkr 20150829_docker-python
 
Introduction to Nodejs
Introduction to NodejsIntroduction to Nodejs
Introduction to Nodejs
 
Replacing "exec" with a type and provider: Return manifests to a declarative ...
Replacing "exec" with a type and provider: Return manifests to a declarative ...Replacing "exec" with a type and provider: Return manifests to a declarative ...
Replacing "exec" with a type and provider: Return manifests to a declarative ...
 
jQuery secrets
jQuery secretsjQuery secrets
jQuery secrets
 
Scaling Symfony2 apps with RabbitMQ - Symfony UK Meetup
Scaling Symfony2 apps with RabbitMQ - Symfony UK MeetupScaling Symfony2 apps with RabbitMQ - Symfony UK Meetup
Scaling Symfony2 apps with RabbitMQ - Symfony UK Meetup
 
Stanford Hackathon - Puppet Modules
Stanford Hackathon - Puppet ModulesStanford Hackathon - Puppet Modules
Stanford Hackathon - Puppet Modules
 
Explaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to ComeExplaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to Come
 

En vedette

Karen White: 360
Karen White: 360Karen White: 360
Karen White: 360360mnbsu
 
Что выбрать Украине? Евросоюз или Таможенный Союз?
Что выбрать Украине? Евросоюз или Таможенный Союз?Что выбрать Украине? Евросоюз или Таможенный Союз?
Что выбрать Украине? Евросоюз или Таможенный Союз?Darius Radkevicius
 
fDi Digital Marketing Awards 2012
fDi Digital Marketing Awards 2012fDi Digital Marketing Awards 2012
fDi Digital Marketing Awards 2012One Columbus
 
Accounting for External Costs in Pricing Freight Transport
Accounting for External Costs in Pricing Freight TransportAccounting for External Costs in Pricing Freight Transport
Accounting for External Costs in Pricing Freight TransportCongressional Budget Office
 
Considering Cumulative Effects Under Nepa
Considering Cumulative Effects Under NepaConsidering Cumulative Effects Under Nepa
Considering Cumulative Effects Under NepaObama White House
 
A Partner is Good to Have, but Difficult to Be
A Partner is Good to Have, but Difficult to BeA Partner is Good to Have, but Difficult to Be
A Partner is Good to Have, but Difficult to Behouseofyin
 
How do we make users happy?
How do we make users happy? How do we make users happy?
How do we make users happy? martina mitz
 
Accountability regulation and leadership in our school system - exploring a t...
Accountability regulation and leadership in our school system - exploring a t...Accountability regulation and leadership in our school system - exploring a t...
Accountability regulation and leadership in our school system - exploring a t...Browne Jacobson LLP
 
Creutzfeldt jakob disease Dr. Muhammad Bin Zulfiqar
Creutzfeldt jakob disease Dr. Muhammad Bin ZulfiqarCreutzfeldt jakob disease Dr. Muhammad Bin Zulfiqar
Creutzfeldt jakob disease Dr. Muhammad Bin ZulfiqarDr. Muhammad Bin Zulfiqar
 
HK CodeConf 2015 - Your WebPerf Sucks
HK CodeConf 2015 - Your WebPerf Sucks HK CodeConf 2015 - Your WebPerf Sucks
HK CodeConf 2015 - Your WebPerf Sucks Holger Bartel
 
WHY PEOPLE BULLSHIT AND WHAT TO DO ABOUT IT
WHY PEOPLE BULLSHIT AND WHAT TO DO ABOUT ITWHY PEOPLE BULLSHIT AND WHAT TO DO ABOUT IT
WHY PEOPLE BULLSHIT AND WHAT TO DO ABOUT ITKevin Duncan
 
Air blockchain café 2016-10-04
Air blockchain café 2016-10-04Air blockchain café 2016-10-04
Air blockchain café 2016-10-04Lykle de Vries
 
Top 16 Books Hemingway Recommends
Top 16 Books Hemingway RecommendsTop 16 Books Hemingway Recommends
Top 16 Books Hemingway RecommendsESSAYSHARK.com
 

En vedette (18)

Cyborg
CyborgCyborg
Cyborg
 
Karen White: 360
Karen White: 360Karen White: 360
Karen White: 360
 
Что выбрать Украине? Евросоюз или Таможенный Союз?
Что выбрать Украине? Евросоюз или Таможенный Союз?Что выбрать Украине? Евросоюз или Таможенный Союз?
Что выбрать Украине? Евросоюз или Таможенный Союз?
 
fDi Digital Marketing Awards 2012
fDi Digital Marketing Awards 2012fDi Digital Marketing Awards 2012
fDi Digital Marketing Awards 2012
 
Accounting for External Costs in Pricing Freight Transport
Accounting for External Costs in Pricing Freight TransportAccounting for External Costs in Pricing Freight Transport
Accounting for External Costs in Pricing Freight Transport
 
Considering Cumulative Effects Under Nepa
Considering Cumulative Effects Under NepaConsidering Cumulative Effects Under Nepa
Considering Cumulative Effects Under Nepa
 
A Partner is Good to Have, but Difficult to Be
A Partner is Good to Have, but Difficult to BeA Partner is Good to Have, but Difficult to Be
A Partner is Good to Have, but Difficult to Be
 
How do we make users happy?
How do we make users happy? How do we make users happy?
How do we make users happy?
 
Dev and Designers intro to Sketch
Dev and Designers intro to SketchDev and Designers intro to Sketch
Dev and Designers intro to Sketch
 
Accountability regulation and leadership in our school system - exploring a t...
Accountability regulation and leadership in our school system - exploring a t...Accountability regulation and leadership in our school system - exploring a t...
Accountability regulation and leadership in our school system - exploring a t...
 
Creutzfeldt jakob disease Dr. Muhammad Bin Zulfiqar
Creutzfeldt jakob disease Dr. Muhammad Bin ZulfiqarCreutzfeldt jakob disease Dr. Muhammad Bin Zulfiqar
Creutzfeldt jakob disease Dr. Muhammad Bin Zulfiqar
 
HK CodeConf 2015 - Your WebPerf Sucks
HK CodeConf 2015 - Your WebPerf Sucks HK CodeConf 2015 - Your WebPerf Sucks
HK CodeConf 2015 - Your WebPerf Sucks
 
Fall Home Prep
Fall Home PrepFall Home Prep
Fall Home Prep
 
WHY PEOPLE BULLSHIT AND WHAT TO DO ABOUT IT
WHY PEOPLE BULLSHIT AND WHAT TO DO ABOUT ITWHY PEOPLE BULLSHIT AND WHAT TO DO ABOUT IT
WHY PEOPLE BULLSHIT AND WHAT TO DO ABOUT IT
 
Air blockchain café 2016-10-04
Air blockchain café 2016-10-04Air blockchain café 2016-10-04
Air blockchain café 2016-10-04
 
Top 16 Books Hemingway Recommends
Top 16 Books Hemingway RecommendsTop 16 Books Hemingway Recommends
Top 16 Books Hemingway Recommends
 
java-oneの話
java-oneの話java-oneの話
java-oneの話
 
Facebook Analytics
Facebook AnalyticsFacebook Analytics
Facebook Analytics
 

Similaire à Dispatch Methods in Clojure

Going to Mars with Groovy Domain-Specific Languages
Going to Mars with Groovy Domain-Specific LanguagesGoing to Mars with Groovy Domain-Specific Languages
Going to Mars with Groovy Domain-Specific LanguagesGuillaume Laforge
 
DIとトレイとによるAndroid開発の効率化
DIとトレイとによるAndroid開発の効率化DIとトレイとによるAndroid開発の効率化
DIとトレイとによるAndroid開発の効率化Tomoharu ASAMI
 
Vk.amberfog.com gtug part1_introduction2_javaandroid_gtug
Vk.amberfog.com gtug part1_introduction2_javaandroid_gtugVk.amberfog.com gtug part1_introduction2_javaandroid_gtug
Vk.amberfog.com gtug part1_introduction2_javaandroid_gtugketan_patel25
 
Suportando Aplicações Multi-tenancy com Java EE
Suportando Aplicações Multi-tenancy com Java EESuportando Aplicações Multi-tenancy com Java EE
Suportando Aplicações Multi-tenancy com Java EERodrigo Cândido da Silva
 
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...Paul King
 
CSharp presentation and software developement
CSharp presentation and software developementCSharp presentation and software developement
CSharp presentation and software developementfrwebhelp
 
Groovy DSLs, from Beginner to Expert - Guillaume Laforge and Paul King - Spri...
Groovy DSLs, from Beginner to Expert - Guillaume Laforge and Paul King - Spri...Groovy DSLs, from Beginner to Expert - Guillaume Laforge and Paul King - Spri...
Groovy DSLs, from Beginner to Expert - Guillaume Laforge and Paul King - Spri...Guillaume Laforge
 
Atlassian Groovy Plugins
Atlassian Groovy PluginsAtlassian Groovy Plugins
Atlassian Groovy PluginsPaul King
 
Living With Legacy Code
Living With Legacy CodeLiving With Legacy Code
Living With Legacy CodeRowan Merewood
 
Java design patterns
Java design patternsJava design patterns
Java design patternsShawn Brito
 
Your Entity, Your Code
Your Entity, Your CodeYour Entity, Your Code
Your Entity, Your CodeDrupalDay
 
Java - A broad introduction
Java - A broad introductionJava - A broad introduction
Java - A broad introductionBirol Efe
 
Android and the Seven Dwarfs from Devox'15
Android and the Seven Dwarfs from Devox'15Android and the Seven Dwarfs from Devox'15
Android and the Seven Dwarfs from Devox'15Murat Yener
 
Aspect oriented programming_with_spring
Aspect oriented programming_with_springAspect oriented programming_with_spring
Aspect oriented programming_with_springGuo Albert
 

Similaire à Dispatch Methods in Clojure (20)

Going to Mars with Groovy Domain-Specific Languages
Going to Mars with Groovy Domain-Specific LanguagesGoing to Mars with Groovy Domain-Specific Languages
Going to Mars with Groovy Domain-Specific Languages
 
DIとトレイとによるAndroid開発の効率化
DIとトレイとによるAndroid開発の効率化DIとトレイとによるAndroid開発の効率化
DIとトレイとによるAndroid開発の効率化
 
Xtext Webinar
Xtext WebinarXtext Webinar
Xtext Webinar
 
Xtext Webinar
Xtext WebinarXtext Webinar
Xtext Webinar
 
Vk.amberfog.com gtug part1_introduction2_javaandroid_gtug
Vk.amberfog.com gtug part1_introduction2_javaandroid_gtugVk.amberfog.com gtug part1_introduction2_javaandroid_gtug
Vk.amberfog.com gtug part1_introduction2_javaandroid_gtug
 
Suportando Aplicações Multi-tenancy com Java EE
Suportando Aplicações Multi-tenancy com Java EESuportando Aplicações Multi-tenancy com Java EE
Suportando Aplicações Multi-tenancy com Java EE
 
core java
core javacore java
core java
 
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
 
CSharp presentation and software developement
CSharp presentation and software developementCSharp presentation and software developement
CSharp presentation and software developement
 
Groovy DSLs, from Beginner to Expert - Guillaume Laforge and Paul King - Spri...
Groovy DSLs, from Beginner to Expert - Guillaume Laforge and Paul King - Spri...Groovy DSLs, from Beginner to Expert - Guillaume Laforge and Paul King - Spri...
Groovy DSLs, from Beginner to Expert - Guillaume Laforge and Paul King - Spri...
 
Atlassian Groovy Plugins
Atlassian Groovy PluginsAtlassian Groovy Plugins
Atlassian Groovy Plugins
 
Living With Legacy Code
Living With Legacy CodeLiving With Legacy Code
Living With Legacy Code
 
Java design patterns
Java design patternsJava design patterns
Java design patterns
 
Your Entity, Your Code
Your Entity, Your CodeYour Entity, Your Code
Your Entity, Your Code
 
Your Entity, Your Code
Your Entity, Your CodeYour Entity, Your Code
Your Entity, Your Code
 
Java - A broad introduction
Java - A broad introductionJava - A broad introduction
Java - A broad introduction
 
Android and the Seven Dwarfs from Devox'15
Android and the Seven Dwarfs from Devox'15Android and the Seven Dwarfs from Devox'15
Android and the Seven Dwarfs from Devox'15
 
Dart Workshop
Dart WorkshopDart Workshop
Dart Workshop
 
Better Understanding OOP using C#
Better Understanding OOP using C#Better Understanding OOP using C#
Better Understanding OOP using C#
 
Aspect oriented programming_with_spring
Aspect oriented programming_with_springAspect oriented programming_with_spring
Aspect oriented programming_with_spring
 

Dernier

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
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
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.pdfUK Journal
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
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
 
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 2024The Digital Insurer
 
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 MenDelhi Call girls
 
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
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
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
 
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
 
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
 
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
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 

Dernier (20)

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
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
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
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
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...
 
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
 
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
 
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
 
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
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
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
 
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
 
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
 
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
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 

Dispatch Methods in Clojure

  • 1. Dispatch in Clojure Carlo Sciolla, Product Lead @ Backbase DISPATCH IN CLOJURE | August 8, 2012 | @skuro
  • 2. (ns aot (:gen-class)) (defn -main [& args] (dorun (map println (seq args)))) javap -c aot.class A quick journey in function calling We all learn to divide our code in functions, and invoke them when it’s their time on the stage of data processing. We define units of computations, ready to be executed. DISPATCH IN CLOJURE | August 8, 2012 | @skuro
  • 3. public static void main(java.lang.String[]); [..] 4:! invokevirtual!#66; [..] 26:!invokestatic! #104; 29:!invokeinterface! #108, 2; [..] 44:!invokespecial!#115; (defn -main [& args] [..] (dorun (map println (seq args)))) The JVM executes our code We’ll leave it to the JVM to figure out which code to actually run upon function call. It’s not always a straightforward job, and there are several ways to get to the code. DISPATCH IN CLOJURE | August 8, 2012 | @skuro
  • 4. public static void main(java.lang.String[]); [..] 4:! invokevirtual!#66; [..] 26:!invokestatic! #104; 29:!invokeinterface! #108, 2; [..] 44:!invokespecial!#115; [..] [clojure.lang.RT] static public ISeq seq(Object coll) Static dispatch When there’s nothing to choose from, the compiler emits a static dispatch bytecode. All calls will always result in the same code being executed. DISPATCH IN CLOJURE | August 8, 2012 | @skuro
  • 5. public static void main(java.lang.String[]); [..] 4:! invokevirtual!#66; [..] 26:!invokestatic! #104; 29:!invokeinterface! #108, 2; [..] 44:!invokespecial!#115; [..] Dynamic dispatch Most often the compiler can’t figure out the proper method implementation to call, and the runtime will get its chance to dynamically dispatch the call. DISPATCH IN CLOJURE | August 8, 2012 | @skuro
  • 6. * dispatch by arity * object oriented inheritance * multimethods * custom is-a hierarchies * protocols The options at hand Clojure provides a rich interface to dynamic dispatch, allowing programmers to have control over the dispatch logic at different degrees to find the optimal balance on the performance trade off scale. DISPATCH IN CLOJURE | August 8, 2012 | @skuro
  • 7. * dispatch by arity * object oriented inheritance (defn sum-them * multimethods ([x y] (+ x y)) * custom is-a hierarchies ([x y z] (+ x y z))) * protocols The good old arity Being a dynamically typed language, Clojure only checks on the number of arguments provided in the function call to find the right implementation to call. DISPATCH IN CLOJURE | August 8, 2012 | @skuro
  • 8. * dispatch by arity (defn stringify [x] * object oriented inheritance (.toString x)) * multimethods * custom is-a hierarchies (stringify (HashMap.)) ; “{}” * protocols (stringify (HashSet.)) ; “[]” More than Java™ Thanks to Clojure intimacy with Java, object inheritance is easily achieved. Thanks to Clojure dynamic typing, it also allows functions to traverse multiple inheritance trees. DISPATCH IN CLOJURE | August 8, 2012 | @skuro
  • 9. (defn stringify* [^HashMap x] (.toString x)) * dispatch by arity * object oriented inheritance (stringify* (HashMap.)) * multimethods => “{}” * custom is-a hierarchies (stringify* (TreeMap.)) * protocols => “{}” (stringify* (HashSet.)) => ClassCastException Forcing virtual dispatch to improve performance Being a dynamic language has a number of benefits, but performance isn’t one of them. To avoid reflection calls needed by default by the dynamic dispatch you can use type hints. DISPATCH IN CLOJURE | August 8, 2012 | @skuro
  • 10. (defn dispatch-fn [{:keys [version]}] * dispatch by arity version) * object oriented inheritance * multimethods (defmulti multi-call * custom is-a hierarchies dispatch-fn) * protocols http://bit.ly/multi-tests Full power Multimethods allow you to define your own dispatch strategy as a plain Clojure function. Their limit is the sky: they perform quite bad, and your dispatch fn can’t be changed or extended in user code. DISPATCH IN CLOJURE | August 8, 2012 | @skuro
  • 11. (defmethod multi-call ::custom-type * dispatch by arity [x] [...]) * object oriented inheritance * multimethods (derive java.util.HashSet * custom is-a hierarchies ::custom-type) * protocols http://bit.ly/multi-tests Inheritance à la carte Java types hierarchies defined outside your code can be “altered” by custom is-a? relationships created as needed. You can either use the default hierarchy or use make-hierarchy to restrict its scope. DISPATCH IN CLOJURE | August 8, 2012 | @skuro
  • 12. (defprotocol Registered (register [this])) * dispatch by arity * object oriented inheritance (extend-type String * multimethods Registered * custom is-a hierarchies (register [this] [...])) * protocols http://bit.ly/proto-tests Inheritance à la carte Java types hierarchies defined outside your code can be “altered” by custom is-a? relationships created as needed. You can either use the default hierarchy or use make-hierarchy to restrict its scope. DISPATCH IN CLOJURE | August 8, 2012 | @skuro
  • 13. * never used when compiling pure Java * moves type checking at run time * the compiler doesn’t resolve the method * user code to perform the dispatch * eligible for JIT optimizations http://bit.ly/headius-invokedynamic Bonus track: invokedynamic Java7 introduced a new bytecode instruction to help JVM languages designers: invokedynamic. There’s a long standing discussion as which benefits it can provide to Clojure. DISPATCH IN CLOJURE | August 8, 2012 | @skuro
  • 14. Q/A DISPATCH IN CLOJURE | August 8, 2012 | @skuro
  • 15. Thanks! Amsterdam Clojurians Carlo Sciolla Product Lead http://skuro.tk @skuro http://bit.ly/amsclojure DISPATCH IN CLOJURE | August 8, 2012 | @skuro

Notes de l'éditeur

  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