什么优势是使用'get'而不是访问地图 [英] what advantage is there to use 'get' instead to access a map

查看:122
本文介绍了什么优势是使用'get'而不是访问地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从此问题继续:按关键字查找惯用clojure地图



使用clojure的地图访问可以通过多种方式完成。

  def m {:a 1} 

(get m:a);; => 1
(:am);; => 1
;; => 1



我知道我主要使用第二种形式,有时第三种,很少

/clojure.org/data_structures#Data%20Structures-Maps%20%28IPersistentMap%29rel =nofollow> clojure网页我们看到


Maps实现IFn,对一个参数(一个键)的invoke()使用
可选的第二个参数(默认值),即映射是
的键的函数。 nil键和值都可以。


有时候在Clojure的引擎盖下看看有什么好处。如果您查看地图中调用的样式,您会看到:





显然调用 valAt 方法。



如果你看看 get 函数在使用地图调用时,是对 clojure.lang.RT.get 的调用,这真的归结为对 valAt 的调用地图(地图实施ILookUp,因为它们是关联):



https://github.com/clojure/clojure/blob/master/src/jvm/clojure/lang/RT.java#L634



对于使用key和not-found-value调用的映射,也是如此。那么,有什么优势呢?由于两种方法都归结到几乎相同,性能明智我不会说什么。它只是语法方便。


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

Maps implement IFn, for invoke() of one argument (a key) with an optional second argument (a default value), i.e. maps are functions of their keys. nil keys and values are ok.

Sometimes it is rewarding to take a look under the hoods of Clojure. If you look up what invoke looks 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 valAt method of a map.

If you look at what the get function does when called with a map, this is a call to clojure.lang.RT.get, and this really boils down to the same call to valAt for 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.

这篇关于什么优势是使用'get'而不是访问地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆