Made the bulk set() function in BitSet a lot faster by applying an appropriate mask to each partition instead of setting each bit individually.

This commit is contained in:
Mike Keesey 2012-07-04 16:00:12 -06:00
parent 5f1b086150
commit 0c806f82b5

View File

@ -97,8 +97,7 @@ public class BitSet implements Serializable, Cloneable {
int currentFirstIndex = fromIndex; int currentFirstIndex = fromIndex;
for (int i = 0; i < numPartitionsToTraverse; ++i) { for (int i = 0; i < numPartitionsToTraverse; ++i) {
int currentToIndex = Math.min(toIndex, (basePartition + i + 1) * BITS_PER_LONG); int currentToIndex = Math.min(toIndex, (basePartition + i + 1) * BITS_PER_LONG);
int currentRange = currentToIndex - currentFirstIndex; long mask = getTrueMask(currentFirstIndex, currentToIndex);
long mask = (((1L << currentRange) - 1L) << (currentFirstIndex % BITS_PER_LONG));
bits[i + basePartition] ^= mask; bits[i + basePartition] ^= mask;
currentFirstIndex = currentToIndex; currentFirstIndex = currentToIndex;
} }
@ -115,6 +114,11 @@ public class BitSet implements Serializable, Cloneable {
} }
} }
private long getTrueMask(int fromIndex, int toIndex) {
int currentRange = toIndex - fromIndex;
return (((1L << currentRange) - 1L) << (fromIndex % BITS_PER_LONG));
}
public void clear(int index) { public void clear(int index) {
int pos = longPosition(index); int pos = longPosition(index);
if (pos < bits.length) { if (pos < bits.length) {
@ -137,8 +141,18 @@ public class BitSet implements Serializable, Cloneable {
} }
public void set(int start, int end) { public void set(int start, int end) {
for (int i = start; i < end; i++) { //TODO remove copypasta
set(i); 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;
} }
} }