按关键字进行惯用的 clojure 地图查找 [英] Idiomatic clojure map lookup by keyword
问题描述
假设我有一个使用关键字作为键的 clojure 映射:
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 up the value associated with the keyword by either using the keyword or the map as a function and the other as its argument:
(my-car :color)
; => "candy-apple red"
(:color my-car)
; => "candy-apple red"
我意识到这两种形式在某些情况下都可以派上用场,但是对于如上所示的直接用法,其中一种形式是否被认为更惯用?
I realize that both forms can come in handy for certain situations, but is one of them considered more idiomatic for straightforward usage like shown above?
推荐答案
(:color my-car)
是相当标准的.这有几个原因,我不会深入研究所有这些.但这里有一个例子.
(: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.
因为:color
是常量,而my-car
不是,hotspot可以完全内联color.invoke(m)
的动态调度code>,它不能用 m.invoke(color)
(在一些 java 伪代码中).
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).
如果 my-car
有时恰好是带有 color
字段的记录而不是普通地图,情况会更好:clojure 编译器可以发出代码来检查嘿,如果 my-car
是 CarType 的实例,那么只需返回 my-car.color
;否则执行所有复杂、缓慢的哈希图查找."
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."
这篇关于按关键字进行惯用的 clojure 地图查找的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!