Testing whether an object is a Java primitive array in Clojure

前端 未结 7 2439
时光说笑
时光说笑 2021-02-08 08:47

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

7条回答
  •  天命终不由人
    2021-02-08 09:22

    Props to all the other answers. Here it is as a one-liner:

    (def byte-array? (partial instance? (Class/forName "[B")))
    

    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:

    "[Z" boolean array
    "[B" byte array
    "[C" char array
    "[D" double array
    "[F" float array
    "[I" integer array
    "[J" long array
    "[S" short array
    

    Since performance was mentioned, here's a small benchmark result of running (time (dotimes [_ 500000] (byte-array? x))), and with byte-array-class def'd

    (def byte-array? (partial instance? (Class/forName "[B")))
    78.518335 msecs
    (defn byte-array? [obj] (instance? byte-array-class obj))
    34.879537 msecs
    (defn byte-array? [obj] (= (type obj) byte-array-class))
    49.68781 msecs
    

    instance? vs type = instance? wins

    partial vs defn = defn wins

    but any of these approaches will likely not be a bottleneck in performance.

提交回复
热议问题