Idiomatic clojure map lookup by keyword

后端 未结 4 881
忘了有多久
忘了有多久 2020-11-29 08:09

Say I have a clojure map that uses keywords as its keys:

(def my-car {:color \"candy-apple red\" :horsepower 450})

I know that I can look u

4条回答
  •  醉酒成梦
    2020-11-29 08:54

    (:color my-car) is fairly standard. There are a few reasons for this, and I won't go into all of them. But here's an example.

    Because :color is a constant, and my-car is not, hotspot can completely inline the dynamic dispatch of color.invoke(m), which it can't do with m.invoke(color) (in some java pseudo-code).

    That gets even better if my-car happens to sometimes be a record with a color field instead of a plain map: the clojure compiler can emit code to check "hey, if my-car is an instance of CarType, then just return my-car.color; otherwise do all the complicated, slow, hashmap lookup."

提交回复
热议问题