How to efficiently convert a Java BitSet to a vector?

You’re just facing the reality of how slow reflection based interrop is:

(set! *warn-on-reflection* true)

(defn bitset->vec
   [bits]
   (->> bits
        .size
        range
        (filter (fn [x] (.get bits x)))
        (into [])))

;> Reflection warning, NO_SOURCE_PATH:6:24 - call to method get can't be resolved (target class is unknown).
;> Reflection warning, NO_SOURCE_PATH:6:8 - reference to field size can't be resolved.

(time (count (bitset->vec bits)))
"Elapsed time: 1016.910122 msecs"

(defn bitset->vec
   [^java.util.BitSet bits]
   (->> bits
        .size
        range
        (filter (fn [x] (.get bits x)))
        (into [])))

(time (count (bitset->vec bits)))
"Elapsed time: 33.692455 msecs"

Tl;DR: Just type hint bits and it will be fast again.

3 Likes