Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java ByteBuffer put vs wrap

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?

like image 250
PerracoLabs Avatar asked Jun 19 '12 08:06

PerracoLabs


2 Answers

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
like image 95
Peter Lawrey Avatar answered Sep 26 '22 21:09

Peter Lawrey


wrap should be much faster, as --if I understand the doc correctly-- it does not copy the byte array, but just sets the member variables (capacity/limit/position). wrap only makes sense, if you already got the byte[] with the desired data from somewhere, of course.

like image 31
datafiddler Avatar answered Sep 22 '22 21:09

datafiddler