Should the contents be already available as ByteBuffer
s, how expensize is creating an array from them?
import java.nio.ByteBuffer;
public class Main
{
public static void main(String[] args) {
ByteBuffer buf1 = ByteBuffer.allocate(666); /*(0)*/
ByteBuffer buf2 = ByteBuffer.allocate(666); /*(0)*/
ByteBuffer buf3 = ByteBuffer.allocate(666); /*(0)*/
ByteBuffer arr[] = new ByteBuffer[]{buf1,buf2,buf3}; /* (1) */
}
}
Array creation shouldn't depend on the sizes of the buffers, right?
An array of objects in Java is actually an array of references (pointers). Conceptually, we think of the array as holding your three ByteBuffer
objects. But actually the array holds only the equivalent of an address in memory where each ByteBuffer
object can be found.
Accessing the array is a two-step process. When you access an element in an array, such as arr[ 2]
, first the reference is located in that position/slot of the array. Then secondly, using that reference, the JVM jumps to the position in memory as pointed by the reference where a particular object lives.
So your array uses very little memory. The array does not duplicate your ByteBuffer
objects. Before your line of code creating the array, you have three ByteBuffer
objects floating around in memory somewhere. And after creating the array, you still have only the same three ByteBuffer
objects floating around in memory.
By the way, the same is true if you used a Collection
such as a List
or Set
rather than an array.