Skip to content

Instantly share code, notes, and snippets.

@rosarinjroy
Created April 10, 2012 20:57
Show Gist options
  • Save rosarinjroy/2354420 to your computer and use it in GitHub Desktop.
Save rosarinjroy/2354420 to your computer and use it in GitHub Desktop.
Convert byte array to long using shifting and ByteArray and compare the performance
package main;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
/**
* The objective is to compute the value of long represented as a sequence of
* bytes using ByteBuffer and by shifting, and compare the performance.
*
*/
public class ByteBufferVersusShifting {
public static long usingByteBuffer(ByteBuffer byteBuffer) {
return byteBuffer.getLong(0);
}
public static long usingShifting(byte[] bytes, int offset) {
long retVal = 0;
retVal |= ((long) bytes[offset + 7] & 0xFF);
retVal <<= 8;
retVal |= ((long) bytes[offset + 6] & 0xFF);
retVal <<= 8;
retVal |= ((long) bytes[offset + 5] & 0xFF);
retVal <<= 8;
retVal |= ((long) bytes[offset + 4] & 0xFF);
retVal <<= 8;
retVal |= ((long) bytes[offset + 3] & 0xFF);
retVal <<= 8;
retVal |= ((long) bytes[offset + 2] & 0xFF);
retVal <<= 8;
retVal |= ((long) bytes[offset + 1] & 0xFF);
retVal <<= 8;
retVal |= ((long) bytes[offset] & 0xFF);
return retVal;
}
public static long timeIt(Runnable r) throws Exception {
long start = System.nanoTime();
r.run();
long end = System.nanoTime();
return (end - start);
}
public static void main(String[] args) throws Exception {
final byte[] bytes = new byte[] { 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x00 };
final ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
byteBuffer.order(ByteOrder.LITTLE_ENDIAN);
final long niterIncrement = 10000000;
// Warm up
for (long i = 0; i < 100000; i++) {
usingShifting(bytes, 0);
}
for (long i = 0; i < 100000; i++) {
usingByteBuffer(byteBuffer);
}
for (int j = 1; j <= 20; j++) {
final long niter = niterIncrement*j;
long shiftingTime = timeIt(new Runnable() {
@Override
public void run() {
for (long i = 0; i < niter; i++) {
usingShifting(bytes, 0);
}
}
});
long byteBufferTime = timeIt(new Runnable() {
@Override
public void run() {
for (long i = 0; i < niter; i++) {
usingByteBuffer(byteBuffer);
}
}
});
System.out.printf("%12d, %12d, %12d, %.2f\n", niter, shiftingTime, byteBufferTime, (double)byteBufferTime/(double)shiftingTime);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment