Search code examples
javaperformanceniobytebuffer

Efficient way to slice ByteBuffer and append data to it


I have an existing ByeBuffer backed by an array. Now I want to get a portion of this ByteBuffer from an offset to the end and then append some data (stored in other byte array) to the end of this sliced ByteBuffer. Assuming I have "offset" in the ByteBuffer and byte array "buffer" which needs to be appended to the ByteBuffer. This is what I am doing now -

                byte[] prevArray = previousByteBuffer.array();

                byte[] newArray = new byte[prevArray.length-offset+buffer.length];
                for(int i=offset; i<prevArray.length; i++){
                    newArray[i-offset] = prevArray[i];
                }
                for(int i=prevArray.length; i<(prevArray.length+len); i++){
                    newArray[i-offset] = buffer[i-prevArray.length];
                }
                ByteBuffer byteBuffer = ByteBuffer.wrap(newArray);

I think what I am doing is highly inefficient. What's the efficient way to achieve this ? Thanks.


Solution

  • The best thing you could do is preallocate your eventual ByteBuffer as large as practical. arraycopy will help, but the what's killing you is re-copying of the original data. If you can use some heuristic to better predict your eventual destination size, you can avoid recopying of data, and speed the entire thing up tremendously.