The most important change is to avoid allocating objects within the method. By the way your micro benchmark didn't reset "start", so the second result includes the time used for the first method. Also, you need to run micro benchmarks multiple times, otherwise the just in time compiler has no chance to run. I suggest to use a method similar to
public static int readMediumInt3(ByteBuffer buf) {
return ((buf.get() & 0xff) << 16) +
((buf.get() & 0xff) << 8) +
((buf.get() & 0xff));
}
The complete code is:
import java.nio.ByteBuffer;
public class Main {
public static int readMediumInt(ByteBuffer in) {
ByteBuffer buf = ByteBuffer.allocate(4);
buf.put((byte) 0x00);
buf.put(in.get());
buf.put(in.get());
buf.put(in.get());
buf.flip();
return buf.getInt();
}
public static int readMediumInt2(ByteBuffer in) {
byte[] bytes = new byte[3];
in.get(bytes);
int val = 0;
val += bytes[0] * 256 * 256;
val += bytes[1] * 256;
val += bytes[2];
if (val < 0) {
val += 256;
}
return val;
}
public static int readMediumInt3(ByteBuffer buf) {
return ((buf.get() & 0xff) << 16) +
((buf.get() & 0xff) << 8) +
((buf.get() & 0xff));
}
public static void main(String[] args) {
Main m = new Main();
for (int i = 0; i < 5; i++) {
// version 1
ByteBuffer buf = ByteBuffer.allocate(4);
buf.putInt(424242);
buf.flip();
long start;
start = System.nanoTime();
for (int j = 0; j < 10000000; j++) {
buf.position(0);
readMediumInt(buf);
}
start = System.nanoTime() - start;
System.out.printf("Ver 1: elapsed: %d ms\n", start / 1000000);
// version 2
ByteBuffer buf2 = ByteBuffer.allocate(4);
buf2.putInt(424242);
buf2.flip();
start = System.nanoTime();
for (int j = 0; j < 10000000; j++) {
buf2.position(0);
readMediumInt2(buf2);
}
start = System.nanoTime() - start;
System.out.printf("Ver 2: elapsed: %d ms\n", start / 1000000);
// version 3
ByteBuffer buf3 = ByteBuffer.allocate(4);
buf3.putInt(424242);
buf3.flip();
start = System.nanoTime();
for (int j = 0; j < 10000000; j++) {
buf3.position(0);
readMediumInt3(buf3);
}
start = System.nanoTime() - start;
System.out.printf("Ver 3: elapsed: %d ms\n", start / 1000000);
}
}
}
My results:
- Ver 1: elapsed: 556 ms
- Ver 2: elapsed: 187 ms
- Ver 3: elapsed: 3 ms