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 withbyte
arrays (even usingArrays.asList()
, which returns meList<Byte[]>
). To fix it I'm just looping and adding abyte
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 theArrayList
. I can't cast fromByte[]
tobyte[]
, 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
andByteArrayOutputStream
. 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>
.