Skip to content

Commit

Permalink
Made the bulk set() function in BitSet a lot faster by applying an ap…
Browse files Browse the repository at this point in the history
…propriate mask to each partition instead of setting each bit individually.
  • Loading branch information
Mike Keesey committed Jul 4, 2012
1 parent 5f1b086 commit 0c806f8
Showing 1 changed file with 18 additions and 4 deletions.
22 changes: 18 additions & 4 deletions classpath/java/util/BitSet.java
Expand Up @@ -97,8 +97,7 @@ public void flip(int fromIndex, int toIndex) {
int currentFirstIndex = fromIndex;
for (int i = 0; i < numPartitionsToTraverse; ++i) {
int currentToIndex = Math.min(toIndex, (basePartition + i + 1) * BITS_PER_LONG);
int currentRange = currentToIndex - currentFirstIndex;
long mask = (((1L << currentRange) - 1L) << (currentFirstIndex % BITS_PER_LONG));
long mask = getTrueMask(currentFirstIndex, currentToIndex);
bits[i + basePartition] ^= mask;
currentFirstIndex = currentToIndex;
}
Expand All @@ -115,6 +114,11 @@ private void enlarge(int newPartition) {
}
}

private long getTrueMask(int fromIndex, int toIndex) {
int currentRange = toIndex - fromIndex;
return (((1L << currentRange) - 1L) << (fromIndex % BITS_PER_LONG));
}

public void clear(int index) {
int pos = longPosition(index);
if (pos < bits.length) {
Expand All @@ -137,8 +141,18 @@ public void set(int index) {
}

public void set(int start, int end) {
for (int i = start; i < end; i++) {
set(i);
//TODO remove copypasta
int basePartition = longPosition(start);
int lastPartition = longPosition(end - 1); //range is [fromIndex, toIndex)
int numPartitionsToTraverse = lastPartition - basePartition + 1;
enlarge(lastPartition);

int currentFirstIndex = start;
for (int i = 0; i < numPartitionsToTraverse; ++i) {
int currentToIndex = Math.min(end, (basePartition + i + 1) * BITS_PER_LONG);
long mask = getTrueMask(currentFirstIndex, currentToIndex);
bits[i + basePartition] |= mask;
currentFirstIndex = currentToIndex;
}
}

Expand Down

0 comments on commit 0c806f8

Please sign in to comment.