diff --git a/src/main/scala/scorex/util/serialization/VLQWriter.scala b/src/main/scala/scorex/util/serialization/VLQWriter.scala index 85e947e..e2c2e9d 100644 --- a/src/main/scala/scorex/util/serialization/VLQWriter.scala +++ b/src/main/scala/scorex/util/serialization/VLQWriter.scala @@ -116,10 +116,19 @@ trait VLQWriter extends Writer { // see https://rosettacode.org/wiki/Variable-length_quantity for implementations in other languages } + // TODO optimize: it is possible to further significantly optimize this method + // by directly packing bits into bytes and putting bytes into the writer. + // this can be done without any additional memory garbage (BitSet, toByteArray, copyOf). @inline override def putBits(xs: Array[Boolean]): this.type = { if (xs.isEmpty) return this - val bitSet = new util.BitSet(xs.length) - xs.zipWithIndex.foreach { case (bool, i) => bitSet.set(i, bool)} + val len = xs.length + val bitSet = new util.BitSet(len) + var i = 0 + while (i < len) { + val bool = xs(i) + bitSet.set(i, bool) + i += 1 + } // pad the byte array to fix the "no bit was set" behaviour // see https://stackoverflow.com/questions/11209600/how-do-i-convert-a-bitset-initialized-with-false-in-a-byte-containing-0-in-java val bytes = util.Arrays.copyOf(bitSet.toByteArray, (xs.length + 7) / 8)