Here is an alternate version, but I'm not sure if it is really faster, depends on nextSetBit .
public int getIntersectionsSize(BitSet bits1, BitSet bits2) { int count = 0; int i = bits1.nextSetBit(0); int j = bits2.nextSetBit(0); while (i >= 0 && j >= 0) { if (i < j) { i = bits1.nextSetBit(i + 1); } else if (i > j) { j = bits2.nextSetBit(j + 1); } else { count++; i = bits1.nextSetBit(i + 1); j = bits2.nextSetBit(j + 1); } } return count; }
The above version is hopefully good enough for the compiler, but you can optimize it manually, I think:
public int getIntersectionsSize(BitSet bits1, BitSet bits2) { int count = 0; for (int i = bits1.nextSetBit(0), j = bits2.nextSetBit(0); i >= 0 && j >= 0; ) { while (i < j) { i = bits1.nextSetBit(i + 1); if (i < 0) return count; } if (i == j) { count++; i = bits1.nextSetBit(i + 1); } while (j < i) { j = bits2.nextSetBit(j + 1); if (j < 0) return count; } if (i == j) { count++; j = bits2.nextSetBit(j + 1); } } return count; }
source share