我应该在clojure中使用defrecord? [英] Where should I use defrecord in clojure?

查看:230
本文介绍了我应该在clojure中使用defrecord?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在clojure程序中使用了很多地图和结构体。

I use many maps and structs in my clojure programs. What are the benefits (apart from performance) of converting these to defrecords?

推荐答案

我认为结构有效地被弃用,所以我不要使用它们。

I consider structs to be effectively deprecated so I don't use them at all.

当我有许多地图实例中使用的固定的一组已知的键,我通常创建一个记录。最大的好处是:

When I have a fixed set of well-known keys used in many map instances, I usually create a record. The big benefits are:


  • 性能

  • 生成的类具有可以打开的类型多重方法或其他情况

  • 通过在defrecord附近使用其他宏机制,我可以获取字段验证,默认值和任何其他需要的东西。


  • 键和值会返回稳定的结果(per-创建)命令

  • Performance
  • Generated class has a type that I can switch on in multimethods or other situations
  • With additional macro machinery around defrecord, I can get field validation, default values, and whatever other stuff I want
  • Records can implement arbitrary interfaces or protocols (maps can't)
  • Records act as maps for most purposes
  • keys and vals return results in stable (per-creation) order

记录的一些缺点:


  • 由于记录是Java类实例(而不是Clojure映射),因此没有结构共享,因此相同的记录结构可能使用比已更改的等效映射结构更多的内存。当你改变一个记录时,还有更多的对象创建/销毁,尽管JVM专门设计用来吃这种短暂的垃圾而不打破汗水。

  • 如果你改变记录在开发过程中,您可能需要更频繁地重新启动REPL来获取这些更改。这通常只是开发过程中的一个问题。

  • 许多现有库尚未更新,以支持记录(postwalk,zip,matchure等)。我们已根据需要添加了此支持。

这篇关于我应该在clojure中使用defrecord?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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