Following up from this question: Idiomatic clojure map lookup by keyword
Map access using clojure can be done in many ways.
(def m {:a 1}
(get m :a) ;; => 1
(:a m) ;; => 1
(m :a) ;; => 1
I know I use mainly the second form, and sometimes the third, rarely the first. what are the advantages (speed/composability) of using each?
From the clojure web page we see that
Sometimes it is rewarding to take a look under the hoods of Clojure. If you look up what
invokelooks like in a map, you see this:https://github.com/clojure/clojure/blob/master/src/jvm/clojure/lang/APersistentMap.java#L196
It apparently calls the
valAtmethod of a map.If you look at what the
getfunction does when called with a map, this is a call toclojure.lang.RT.get, and this really boils down to the same call tovalAtfor a map (maps implement ILookUp because they are Associatives):https://github.com/clojure/clojure/blob/master/src/jvm/clojure/lang/RT.java#L634.
The same is true for a map called with a key and a not-found-value. So, what is the advantage? Since both ways boil down to pretty much the same, performance wise I would say nothing. It’s just syntactic convenience.