Working with the Android Profiler tool, I’ve discovered that I’m using lots of ByteBuffers in a performance critical area of my code. I’ve worked on optimizing as much as possible of the largest performance hits (haven’t been forced to go to stuff like loop optimization yet) and the ByteBuffer code looks like it could easily be replaced with another/a better solution.
The Problem: Getting an int from 4 consecutive bytes located in the ByteBuffer stream, which could be of any length, currently done (seen below, specifically //<<< parts) with a temp ByteBuffer and grabbing needed bytes to form an int. Is there any simpler process?
private int peekStreamData(ByteBuffer stream, int count) {
int data = 0;
int stream_field = streamField;
int stream_field_bit_index = streamFieldBitIndex;
byte[] streamArr = stream.array();
ByteBuffer bb = ByteBuffer.allocate(4);
while (count > (32 - stream_field_bit_index) && streamIndex < (imageStream.capacity() >> 2)) {
data = (data << (32 - stream_field_bit_index)) | ( stream_field >>> stream_field_bit_index);
count -= 32 - stream_field_bit_index;
bb.put(0,streamArr[streamIndex * 4 + 3]); //<<<
bb.put(1,streamArr[streamIndex * 4 + 2]); //<<<
bb.put(2,streamArr[streamIndex * 4 + 1]); //<<<
bb.put(3,streamArr[streamIndex * 4 + 0]); //<<<
stream_field = bb.getInt(); //<<<
stream_field_bit_index = 0;
}
if (count > 0)
data = (data << count) | (stream_field >>> (32 - count));
return data;//data;
}
Please feel free to point out any mistakes. I’ve never worked with ByteBuffers until quite recently and would love to learn.
Have you tried:
or:
depending on endiannes.
EDIT: In Java
byteis signed, so they need masking. Corrected.