BitSet bitSet = BitSet.valueOf(new long[] {123});
int count = 0;
int max = 0;
for (int i=0; i < bitSet.size(); i++) {
if(bitSet.get(i)) {
count++;
} else {
max = Math.max(max, count);
count = 0;
}
}
System.out.println(max);
So I have prepared JMH benchmark:
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 10, time = 1, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Fork(1)
@State(Scope.Benchmark)
public class MyBenchmark {
@Param({"0", "1", "255", "4294967295", "-1"})
public long value;
@Benchmark
public int testBitSet() {
int count = 0;
int max = 0;
BitSet bitSet = BitSet.valueOf(new long[]{value});
for (int i = 0; i < bitSet.size(); i++) {
if (bitSet.get(i)) {
count++;
} else {
max = Math.max(max, count);
count = 0;
}
}
return max;
}
@Benchmark
public int testBitWiseOperation() {
int max = 0;
int count = 0;
while (value > 0) {
if ((value & 1) == 1) count++;
else {
if (count > max) max = count;
count = 0;
}
if (count > max) max = count;
value = value >> 1;
}
return max;
}
@Benchmark
public int testRecursion() {
return getMaxBits(value);
}
public static int getMaxBits(long number) {
return accGetMaxBits(number, 0);
}
private static int accGetMaxBits(long number, int accum) {
if (number == 0) return accum;
accum += 1;
return accGetMaxBits(number & (number >>> 1), accum);
}
}
There are results here:
# Run complete. Total time: 00:03:49
Benchmark (value) Mode Cnt Score Error Units
MyBenchmark.testBitSet 0 avgt 5 3,570 ? 0,019 ns/op
MyBenchmark.testBitSet 1 avgt 5 84,515 ? 2,188 ns/op
MyBenchmark.testBitSet 255 avgt 5 85,238 ? 0,581 ns/op
MyBenchmark.testBitSet 4294967295 avgt 5 80,629 ? 0,816 ns/op
MyBenchmark.testBitSet -1 avgt 5 66,905 ? 1,446 ns/op
MyBenchmark.testBitWiseOperation 0 avgt 5 2,200 ? 0,297 ns/op
MyBenchmark.testBitWiseOperation 1 avgt 5 2,164 ? 0,011 ns/op
MyBenchmark.testBitWiseOperation 255 avgt 5 2,166 ? 0,030 ns/op
MyBenchmark.testBitWiseOperation 4294967295 avgt 5 2,172 ? 0,047 ns/op
MyBenchmark.testBitWiseOperation -1 avgt 5 2,164 ? 0,028 ns/op
MyBenchmark.testRecursion 0 avgt 5 2,171 ? 0,015 ns/op
MyBenchmark.testRecursion 1 avgt 5 2,460 ? 0,029 ns/op
MyBenchmark.testRecursion 255 avgt 5 9,546 ? 0,090 ns/op
MyBenchmark.testRecursion 4294967295 avgt 5 31,357 ? 0,389 ns/op
MyBenchmark.testRecursion -1 avgt 5 66,708 ? 0,349 ns/op
On the face of it my solution is lose, but if you have really big bit-array, size of which more than size of long?
p.s. - any concern on code are welcome.