Using deftype to create a wrapper class for byte arrays I want to create a wrapper class for byte arrays so that I can use them as keys in fastutil's Object2LongAVLTreeMap. I have created a wrapper like this:

(deftype Bytes [^bytes ba]
  Comparable
  (compareTo
    [this other]
    (let [m (alength ^bytes (.ba this))
          n (alength ^bytes (.ba other))
          l (min m n)]
      (loop [i 0]
        (if (&lt; i l)
          (let [a (aget ^bytes (.ba ^Bytes this) i)
                b (aget ^bytes (.ba ^Bytes other) i)
                d (compare a b)]
            (if (zero? d)
              (recur (inc i))
              d))
          (compare m n))))))


The wrapper needs to implement Comparable for the insertions in the AVL Tree.

I am looking for feedback regarding my overall approach and my implementation of compareTo. I will be inserting lots of entries into the tree so I don't want to be creating unnecessary objects, etc. during the comparison.

EDIT: I believe the code above has a bug. See my comment below.
First, your calls to .ba aren't being resolved for other, so that's forcing use of reflection. If you run lein check, you'll see:

Reflection warning, thread_test.clj:22:22 - reference to field ba on java.lang.Object can't be resolved.


This has the potential to slow the method down, although it only happens once per call, so the effect wouldn't be huge.

Use explicit type hints to ensure it knows what types you're working with, just like you did below that:

(let [m (alength ^bytes (.ba ^Bytes this))
      n (alength ^bytes (.ba ^Bytes other))


I tried type hinting the parameters instead, and got an error I've never gotten before. I think it was looking for a compareTo with Object parameters, so saying the parameters were Bytes was throwing it.



Other than that, I don't see anything performance related. I'll just point out, in case you don't know, this' ba is actually in scope. You can use it directly which gets rid of some bulk, although makes some of the code less symmetrical:

(deftype Bytes [^bytes ba]
  Comparable
  (compareTo
    [_ other]
    (let [m (alength ba) ; Here
          n (alength ^bytes (.ba ^Bytes other))
          l (min m n)]
      (loop [i 0]
        (if (&lt; i l)
          (let [a (aget ba i) ; And here
                b (aget ^bytes (.ba ^Bytes other) i)
                d (compare a b)]
            (if (zero? d)
              (recur (inc i))
              d))
          (compare m n))))))