SlideShare a Scribd company logo
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

More Related Content

PDF
Alfresco the clojure way -- Slides from the Alfresco DevCon2011
PDF
Clojure and the Web
ODP
Clojure: Practical functional approach on JVM
PDF
Introduction to clojure
PDF
Create your own PHP extension, step by step - phpDay 2012 Verona
ZIP
Oral presentation v2
KEY
Alfresco the clojure way
PPTX
iSoligorsk #3 2013
Alfresco the clojure way -- Slides from the Alfresco DevCon2011
Clojure and the Web
Clojure: Practical functional approach on JVM
Introduction to clojure
Create your own PHP extension, step by step - phpDay 2012 Verona
Oral presentation v2
Alfresco the clojure way
iSoligorsk #3 2013

What's hot (19)

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

Viewers also liked (18)

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

Similar to Dispatch in Clojure (20)

PDF
Going to Mars with Groovy Domain-Specific Languages
PDF
DIとトレイとによるAndroid開発の効率化
PDF
Xtext Webinar
PDF
Xtext Webinar
PDF
Vk.amberfog.com gtug part1_introduction2_javaandroid_gtug
PDF
Suportando Aplicações Multi-tenancy com Java EE
PPT
core java
PDF
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
PPTX
CSharp presentation and software developement
KEY
Groovy DSLs, from Beginner to Expert - Guillaume Laforge and Paul King - Spri...
PDF
Atlassian Groovy Plugins
PDF
BoxLang JVM Language : The Future is Dynamic
PDF
Living With Legacy Code
PDF
Java design patterns
PDF
Your Entity, Your Code
PDF
Your Entity, Your Code
PPTX
Java - A broad introduction
PDF
Android and the Seven Dwarfs from Devox'15
PDF
Dart Workshop
PPTX
Better Understanding OOP using C#
Going to Mars with Groovy Domain-Specific Languages
DIとトレイとによるAndroid開発の効率化
Xtext Webinar
Xtext Webinar
Vk.amberfog.com gtug part1_introduction2_javaandroid_gtug
Suportando Aplicações Multi-tenancy com Java EE
core java
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
CSharp presentation and software developement
Groovy DSLs, from Beginner to Expert - Guillaume Laforge and Paul King - Spri...
Atlassian Groovy Plugins
BoxLang JVM Language : The Future is Dynamic
Living With Legacy Code
Java design patterns
Your Entity, Your Code
Your Entity, Your Code
Java - A broad introduction
Android and the Seven Dwarfs from Devox'15
Dart Workshop
Better Understanding OOP using C#

Recently uploaded (20)

PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PPTX
Cloud computing and distributed systems.
PDF
NewMind AI Monthly Chronicles - July 2025
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PPT
Teaching material agriculture food technology
PDF
Review of recent advances in non-invasive hemoglobin estimation
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PDF
Approach and Philosophy of On baking technology
PDF
Machine learning based COVID-19 study performance prediction
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
CIFDAQ's Market Insight: SEC Turns Pro Crypto
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
Dropbox Q2 2025 Financial Results & Investor Presentation
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Cloud computing and distributed systems.
NewMind AI Monthly Chronicles - July 2025
Building Integrated photovoltaic BIPV_UPV.pdf
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Per capita expenditure prediction using model stacking based on satellite ima...
Teaching material agriculture food technology
Review of recent advances in non-invasive hemoglobin estimation
The AUB Centre for AI in Media Proposal.docx
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
Approach and Philosophy of On baking technology
Machine learning based COVID-19 study performance prediction
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
How UI/UX Design Impacts User Retention in Mobile Apps.pdf

Dispatch 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

Editor's Notes