开发者

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:

  1. 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).
  2. Call slice() on the buffer to create a new buffer that shares the backing store but is offset.
  3. Call asLongBuffer() or asDouble() buffer on the new buffer.
  4. 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜