Dump one Double array and two Long arrays into ByteBuffer in Java
I want to dump one Double array and two Long arrays i开发者_运维技巧nto a bytebuffer. I could use a loop and do
double[] arr1 = new double[size];
long[] arr2 = new long[size];
long[] arr3 = new long[size];
for(int i=0;i<size;i++){
buffer.putDouble(arr1[i]);
buffer.putLong(arr2[i]);
buffer.putLong(arr3[i]);
}
This doesn't seem efficient. Is there a way to balk dump them?
If you truly want to "bulk dump" the data, rather than interleave it in some application-dependent manner, then you can create LongBuffer
and DoubleBuffer
views into your ByteBuffer
. The general procedure is as follows:
- Call
position()
to set the position of the buffer to wherever you want to store the array (you'll have to calculate this based on the size of the primitives). - Call
slice()
on the buffer to create a new buffer that shares the backing store but is offset. - Call
asLongBuffer()
orasDouble()
buffer on the new buffer. - Call the bulk
put()
method on the buffer created in step 3.
This process is a convenience, not a performance enhancement. Unless you're talking tens of millions of elements, you're unlikely to see any improvement at all, and even then you're probably looking at microseconds.
精彩评论