Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Direct Memory vs On Heap in Java
import java.nio.ByteBuffer;
import java.util.Random;
public class BufferPerformanceComparison {
public final static int MEGA_BYTE = 1024 * 1024;
public final static long GIGA_BYTE = MEGA_BYTE * 1024;
private final ByteBuffer heapByteBuffer;
private final ByteBuffer offHeapByteBuffer;
private final long dataToLoad;
private final int bufferSize;
private final Random random = new Random();
private final byte[] base = "I've heard direct buffers are really slow. Are they right or are they wrong. Because if they are right I want to be careful using them and if they are wrong I want to leverage them when I can."
.getBytes();
public BufferPerformanceComparison(int bufferSize, long dataToLoad) {
this.heapByteBuffer = ByteBuffer.allocate(bufferSize);
this.offHeapByteBuffer = ByteBuffer.allocateDirect(bufferSize);
this.dataToLoad = dataToLoad;
this.bufferSize = bufferSize;
}
public void start() {
for (int round = 0; round < 4; round++) {
boolean isWarmup = round == 0;
loadByteBuffer(heapByteBuffer, dataToLoad, !isWarmup, "ONHEAP");
loadByteBuffer(offHeapByteBuffer, dataToLoad, !isWarmup, "DIRECT");
}
}
private void loadByteBuffer(ByteBuffer byteBuffer, long dataToLoad,
boolean printResults, String type) {
long bytesWritten = 0;
long start = System.currentTimeMillis();
int writePosition = random.nextInt(bufferSize - (base.length + 1));
int readPosition = random.nextInt(bufferSize - (base.length + 1));
byte[] readArray = new byte[base.length];
int count = 0;
while (bytesWritten < dataToLoad) {
count++;
if (count % 10 == 0) {
writePosition = random.nextInt(bufferSize - (base.length + 1));
}
bytesWritten += base.length;
byteBuffer.position(writePosition);
byteBuffer.put(base);
byteBuffer.position(readPosition);
byteBuffer.get(readArray, 0, base.length);
}
if (printResults)
System.out.println("Type: " + type + " Took: "
+ (System.currentTimeMillis() - start) + " to write and read: "
+ bytesWritten);
}
public static void main(String[] args) throws Exception {
new BufferPerformanceComparison(50 * MEGA_BYTE, 10L * GIGA_BYTE)
.start();
}
}
/// Output for 1.6 ghz notebook ///
Type: ONHEAP Took: 8978 to write and read: 10737418368
Type: DIRECT Took: 9223 to write and read: 10737418368
Type: ONHEAP Took: 8827 to write and read: 10737418368
Type: DIRECT Took: 9283 to write and read: 10737418368
Type: ONHEAP Took: 8813 to write and read: 10737418368
Type: DIRECT Took: 9604 to write and read: 10737418368
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment