From 0c806f82b500b2f74bd40a6fe72457c7ff10e58c Mon Sep 17 00:00:00 2001 From: Mike Keesey Date: Wed, 4 Jul 2012 16:00:12 -0600 Subject: [PATCH] Made the bulk set() function in BitSet a lot faster by applying an appropriate mask to each partition instead of setting each bit individually. --- classpath/java/util/BitSet.java | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/classpath/java/util/BitSet.java b/classpath/java/util/BitSet.java index e45fbee355..789428a30b 100644 --- a/classpath/java/util/BitSet.java +++ b/classpath/java/util/BitSet.java @@ -97,8 +97,7 @@ public class BitSet implements Serializable, Cloneable { 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; } @@ -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) { int pos = longPosition(index); if (pos < bits.length) { @@ -137,8 +141,18 @@ public class BitSet implements Serializable, Cloneable { } 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; } }