Idiomatic clojure map lookup by keyword

(: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.”

Leave a Comment