Java ByteBuffer put vs wrap

PerracoLabs picture PerracoLabs · Jun 19, 2012 · Viewed 11.2k times · Source

What is the fastest way to fill up a pre-allocated ByteBuffer in Java?

I first set the size of the byte buffer with allocateDirect(), this only needs to be done once. After, I need to fill it up continuously (recycling it) as fast as possible with new data which arrives as a byte[] array, around every 5ms, and without eating memory as I have already pre-allocated the byte buffer. At the moment, I use the put() instruction, which in my system takes around 100ms to complete. Is there another way to fill up the byte buffer? Does thewrap() function run faster without re-allocating the array?

Answer

Peter Lawrey picture Peter Lawrey · Jun 19, 2012

I would hope you mean byte[] not Byte[]

A put() is the fastest way to copy a byte[] into a ByteBuffer. An even faster way is to write into the ByteBuffer in the first place and not use a byte[] at all.

If the copy is taking 100ms, perhaps you are copying too much data. In this test it copies 1 MB in 128 micro-seconds.

ByteBuffer bb = ByteBuffer.allocateDirect(1024 * 1024);
byte[] bytes = new byte[bb.capacity()];

int runs = 50000;
long start = System.nanoTime();
for (int i = 0; i < runs; i++) {
    bb.clear();
    bb.put(bytes);
}
long time = System.nanoTime() - start;
System.out.printf("Average time to copy 1 MB was %.1f us%n", time / runs / 1e3);

prints

Average time to copy 1 MB was 128.9 us