0

I am reading a binary file that has structure :

(integer)(byte[])

The integer represents the size of the byte array that comes next. To avoid allocate all time a byte array, i just allocate when the size of the next read is greater than the last one.

int sz = rawBuffer.getInt();
if (sz > lSz){  //lSz is a class variable
   buffer = new byte[sz];
   lSz = sz;
}
rawBuffer.get(buffer, 0, sz);

The problem is that the buffer has always the maximum size. If a read a byte array of size 5 and the a byte array of size 3, the buffer.length is going to be 5.

Is there anyway to resize the buffer, without need to realocate? Or is it better to have another structure that holds the efective size of the array, like a ByteBuffer for example.

2
  • 1
    Is memory really a critical issue here? Have you considered using an ArrayList? Commented Jul 7, 2015 at 11:51
  • The problem is emory allocation overhead. I am going to do it millions of time. Commented Jul 7, 2015 at 14:31

1 Answer 1

1

I don't think there would be a way to resize the buffer without the process of reallocation. So if the size of the buffer is critical for you, you can try changing your

if (sz > lSz){  //lSz is a class variable
   buffer = new byte[sz];
   lSz = sz;
}

to

if (sz != lSz){
   buffer = new byte[sz];
   lSz = sz;
}

Good Luck.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.