Skip to content

Commit 9444a25

Browse files
author
geompokon@csd.auth.gr
committed
improve countOnes() method: no boxed booleans and replace stream with loop
1 parent 168d8f6 commit 9444a25

File tree

1 file changed

+9
-8
lines changed

1 file changed

+9
-8
lines changed

src/main/java/io/github/abductcows/bitarray/BitArray.java

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -540,16 +540,17 @@ private int longsRequiredForNBits(int nBits) {
540540
public int countOnes() {
541541
if (isEmpty()) return 0;
542542
int oneCount = 0;
543-
int limit = longsRequiredForNBits(size()) - 1;
543+
int limit = longsRequiredForNBits(size()) - 1; // all full longs
544544

545-
oneCount += Arrays.stream(data)
546-
.limit(limit)
547-
.map(Long::bitCount)
548-
.sum();
545+
for (int i = 0; i < limit; i++) {
546+
oneCount += Long.bitCount(data[i]);
547+
}
548+
549+
// last occupied long, not filled
550+
int remainingBits = elements - limit * BITS_PER_LONG;
549551

550-
int remainingBitsIndex = limit * BITS_PER_LONG;
551-
for (int i = remainingBitsIndex; i < elements; i++) {
552-
if (get(i)) {
552+
for (int i = 0; i < remainingBits; i++) {
553+
if (getBit(limit, i)) {
553554
oneCount++;
554555
}
555556
}

0 commit comments

Comments
 (0)