Reputation: 303
Basically, my situation is this:
ByteBuffer
object called inQueue. This contains whatever the most recent stream of data isbyte[]
object then processed separatelyNow my question boils down to this: is copying the remaining buffer data (the payload) to a byte[]
array bad for performance?
Here's what it would look like:
// pretend we're reading the packet ID and length
// int len = LENGTH OF PACKET PAYLOAD
/*
* Mark the starting position of the packet's payload.
*/
int pos = inQueue.position();
byte[] payload = new byte[len];
inQueue.get(payload);
// Process the packet's payload here
/*
* Set the inQueue buffer to the length added to the previous position
* so as to move onto the next packet to process.
*/
inQueue.position(pos + len);
As you can see, I'm essentially doing this:
byte[]
objectMy concern is that, in doing this, I'm wasting memory by copying the buffer. Keep in mind the packets used will never exceed 500 bytes and are often under 100 bytes.
Is my concern valid, or am I being performance-paranoid? :p
Upvotes: 2
Views: 1286
Reputation: 310957
You should avoid it. That's the whole reason for the ByteBuffer design: to avoid data copies.
What exactly do you mean by 'process payload here'?
With a little rearrangement of whatever happens in there, you should be able to do that directly in the ByteBuffer, calling flip()
first, one or more get()
s to get the data you require, and compact()
afterwards (clear()
if you're sure it's empty), without an intermediate copy step into yet another byte[] array.
Upvotes: 1
Reputation: 776
Not only is this unnecessary but, to answer your question, no you won't notice a performance change even when scaling up.
Upvotes: 0