Bladerunner
Bladerunner

Reputation: 97

What is the best way to store a byte array in memory

Somewhere in my server transaction I receive from some backend job a byte array that represents a pdf document.
Later on in the transaction that pdf needs to be written to a client. But at the moment I have that byte array and I want to store it in memory until the pdf file needs to be written to the client.
What is the best way to deal with a byte array?
Create a modelobject and keep the byte array there as a plain byte array?
So for example like this:

public class PdfDocument {
    private byte[] bytearray;
    private String pdftitle;
}

Or is there a better Java Object than just keeping it in memory as a plain byte array? Like ByteBuffer or something else.

Thanks

Upvotes: 1

Views: 2491

Answers (2)

Ilya
Ilya

Reputation: 728

The variable "bytearray" is a reference to an object of class Array. Reference takes up very little memory space.

Upvotes: 0

steffen
steffen

Reputation: 17058

It depends on how you receive the data and whether it's changed in some way:

  1. It sounds like you already have the byte array from backend. In that case I think your simple class would be the most efficient way to keep it in memory as it wouldn't consume considerable extra memory (just some few bytes for the PdfDocument object itself).
  2. You should take however into consideration whether the backend guarantees that it won't change the array later. If that's not the case, or if you want to be safe, you could create a copy with Arrays.copyOf:

    byte[] bytearray = Arrays.copyOf(bytearray, bytearray.length);
    

It seems like you're searching for something more fancy, but I guess your class is perfectly fine here.

Upvotes: 1

Related Questions