Clojure 中测试对象是否为 Java 原始数组
Clojure 中检测对象是否为 Java 原始数组的最佳方法是什么?
我需要这个的原因是对原始数组进行一些特殊处理,这可能看起来像这样:
(if (byte-array? object)
(handle-byte-array object))
它是一段对性能相当敏感的代码,所以如果可能的话,我宁愿避免反射。
What's the best way to detect whether an object is a Java primitive array in Clojure?
The reason I need this is to do some special handling for primitive arrays, which might look something like:
(if (byte-array? object)
(handle-byte-array object))
It's in a fairly performance-sensitive piece of code so I'd rather avoid reflection if at all possible.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
您可以使用反射一次从名称中获取类,缓存它然后
其余的与那个比较
you can use reflection once to get the class from the name, cache this and then
compare the rest to that
对于特定情况,您可以使用类似以下内容:
For particular cases, you could use something like the following:
要在不使用反射的情况下检查字节数组,您可以这样做:
不完全确定原因,但您甚至可以使用
^:const
内联字节数组类型。To check for a byte array without the use of reflection you can do this:
Not exactly sure why, but you can even inline the byte-array-type with
^:const
.还是普通的旧
实例?
:Or plain old
instance?
:正如 Arthur Ulfeldt 所指出的,您可以使用
Class/forName
,例如,如下所示:如果您想在缓存类时避免使用
"[B"
等魔术字符串,您可以将class
应用于现有的数组对象:As pointed by Arthur Ulfeldt, you can use
Class/forName
, for example, like here:If you want to avoid magic strings like
"[B"
when caching the classes, you can applyclass
to an existing array object:支持所有其他答案。这里只是简单介绍一下:
对于其他原语,请参阅 http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#getName%28%29(或 java 规范)。或者只是按照 Gerrit 建议的
(type (xyz-array 0))
进行操作。具体来说,您可以使用:既然提到了性能,这里是运行
(time (dotimes [_ 500000] (byte-array? x)))
的一个小基准测试结果,并使用byte-array -class
def'd实例?
vs类型
= 实例?获胜partial
与defn
= defn 获胜,但这些方法中的任何一种都可能不会成为性能瓶颈。
Props to all the other answers. Here it is as a one-liner:
For other primitives, refer to http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#getName%28%29 (or the java spec). Or just do what Gerrit suggests with
(type (xyz-array 0))
. Specifically you can use:Since performance was mentioned, here's a small benchmark result of running
(time (dotimes [_ 500000] (byte-array? x)))
, and withbyte-array-class
def'dinstance?
vstype
= instance? winspartial
vsdefn
= defn winsbut any of these approaches will likely not be a bottleneck in performance.
从 Clojure 1.9 开始,您可以使用
bytes?
字节?文档链接Since Clojure 1.9, you can use
bytes?
bytes? doc link