Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - ByteBuffer or ArrayList<Byte>?

Recently I created a wrapper to read and write data into a byte array. To do it, I've been using an ArrayList<Byte>, but I was wondering if this is the most efficent way to do it, because:

  • addAll() doesn't work with byte arrays (even using Arrays.asList(), which returns me List<Byte[]>). To fix it I'm just looping and adding a byte at each loop, but I suppose this supposes a lot of function calls and so it has a performance cost.
  • The same happens for getting a byte[] from the ArrayList. I can't cast from Byte[] to byte[], so I have to use a loop for it.
  • I suppose storing Byte instead of byte uses more memory.

I know ByteArrayInputStream and ByteArrayOutputStream could be used for this, but it has some inconvenients:

  • I wanted to implement methods for reading different data types in different byte order (for example, readInt, readLEInt, readUInt, etc), while those classes only can read / write a byte or a byte array. This isn't really a problem because I could fix that in the wrapper. But here comes the second problem.
  • I wanted to be able to write and read at the same time because I'm using this to decompress some files. And so to create a wrapper for it I would need to include both ByteArrayInputStream and ByteArrayOutputStream. I don't know if those could be syncronized in some way or I'd have to write the entire data of one to the other each time I wrote to the wrapper.

And so, here comes my question: would using a ByteBuffer be more efficient? I know you can take integers, floats, etc from it, even being able to change the byte order. What I was wondering is if there is a real performance change between using a ByteBuffer and a ArrayList<Byte>.

like image 680
eric.m Avatar asked Jul 16 '15 12:07

eric.m


1 Answers

Definitely ByteBuffer or ByteArrayOutputStream. In your case ByteBuffer seems fine. Inspect the Javadoc, as it has nice methods, For putInt/getInt and such, you might want to set order (of those 4 bytes)

byteBuffer.order(ByteBuffer.LITTLE_ENDIAN);

With files you could use getChannel() or variants and then use a MappedByteBuffer.

A ByteBuffer may wrap a byte array, or allocate.

like image 133
Joop Eggen Avatar answered Nov 02 '22 07:11

Joop Eggen