Skip to content

Commit

Permalink
some optimisation in putBits
Browse files Browse the repository at this point in the history
  • Loading branch information
aslesarenko committed Oct 9, 2020
1 parent d48bb1a commit 46d58b5
Showing 1 changed file with 11 additions and 2 deletions.
13 changes: 11 additions & 2 deletions src/main/scala/scorex/util/serialization/VLQWriter.scala
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down

0 comments on commit 46d58b5

Please sign in to comment.