I am decomposing a single long into a long[] of single bit longs by
public static int decompose(long[] buffer, long base) {
int count = Long.bitCount(base);
for (int i=0; i<count; i++) {
base ^= (buffer[i] = Long.lowestOneBit(base));
}
return count;
}
but I feel like there might be a faster way to do this, since it seems like there are some repeated steps. For example, counting the bits should already come pretty close to getting all the info needed to populate the result.
Any suggestions? I’m familiar with the premature optimization mantra, hence why I’m not pushing my solution any further on my time, but perhaps someone else has seen this before or is addicted to optimization…EDIT: please run any suggestions through the test harness Mark provided below. I am more than a bit surprised that my first inkling is actually holding up.
test code, which is inside a JUnit method:
Random rng = new Random();
long size = 0;
long[] hold = new long[Long.SIZE];
System.out.println("init:"+Long.toBinaryString(BitTwiddling.bitmask(rng.nextInt(Long.SIZE)))); //initialize BitTwiddling internals
long start = System.currentTimeMillis();
for (int i=0; i<compareIterations; i++) size+= BitTwiddling.decompose(hold,rng.nextInt(Integer.MAX_VALUE));
long delta = System.currentTimeMillis() - start;
double base = (double)size/delta;
size = 0;
start = System.currentTimeMillis();
for (int i=0; i<compareIterations; i++) size += BitTwiddling.decomposeAlt(hold, rng.nextInt(Integer.MAX_VALUE));
long delta2 = System.currentTimeMillis() - start;
double base2 = (double)size/delta2;
then compare base and base2
Here’s the harness I’m using at the moment.
I consistently get the code in the question (Method 1) to perform significantly faster.Currently Mark Peters’ answer is the fastest normally, but Carl’s is faster with the-serverflag set. Also, mikera’s gets considerably more competitive in server mode (though still slower than Carl/Mark’s).Sample output
Which method is best depends on the situation.
Non-server, 32-bit JVM
Winner: MarkPeters
Server, 32-bit JVM
Winner: Carl
Server (implicit or explicit), 64-bit JVM
Winner: MarkPetersServer64Bit
Note: there is no comparable 64-bit JVM that can run in non-server mode to my knowledge. See here: