connergdavis
connergdavis

Reputation: 303

Java: Is copying a ByteBuffer to a byte[] array a performance no-no?

Basically, my situation is this:

  1. Server streams data from the client connection to a ByteBuffer object called inQueue. This contains whatever the most recent stream of data is
  2. Server must process the data in each of these streams and expect a packet of data in a specific format
  3. The payload of data is to be read into a byte[] object then processed separately

Now 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:

  1. Mark the position of the complete buffer as it were just before the payload
  2. Copy the contents of inQueue as far as the payload goes to a separate byte[] object
  3. Set the complete buffer's position to after the payload we just read so we can read more packets

My 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

Answers (2)

user207421
user207421

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

Mitch Connor
Mitch Connor

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

Related Questions