JavaでByteBufferへのコピーを行う際の速度を簡単に比較してみました。java.nio.ByteBuffer#put(byte)で1byteずつ書き込んでいくのでなければ大体同じですね。
Heap上のbyte arrayをコピー
java.nio.ByteBuffer#put(byte[], int, int)
byte[] bs = new byte[256 * 1024 * 1024]; ByteBuffer src = ByteBuffer.wrap(bs); ByteBuffer dst = ByteBuffer.allocate(bs.length); long start = System.currentTimeMillis(); dst.put(src.array(), 0, src.remaining()); System.out.println("heap.byte_array: ByteBuffer.put(byte[], int, int): " + (System.currentTimeMillis() - start));
=> heap.byte_array: ByteBuffer.put(byte[], int, int): 73
java.nio.ByteBuffer#put(java.nio.ByteBuffer)
dst.put(src);
System.out.println("heap.byte_array: ByteBuffer.put(java.nio.ByteBuffer): " + (System.currentTimeMillis() - start));
=> heap.byte_array: ByteBuffer.put(java.nio.ByteBuffer): 69
java.nio.ByteBuffer#put(byte) with loop
for (int i = 0; i < src.remaining(); i++) dst.put(src.get()); System.out.println("heap.byte_array: ByteBuffer.put(byte): " + (System.currentTimeMillis() - start));
=> heap.byte_array: ByteBuffer.put(byte): 380
Heap上のByteBufferをコピー
java.nio.ByteBuffer#put(byte[], int, int)
ByteBuffer src = ByteBuffer.allocate(256 * 1024 * 1024); ByteBuffer dst = ByteBuffer.allocate(256 * 1024 * 1024); long start = System.currentTimeMillis(); dst.put(src.array(), 0, src.remaining()); System.out.println("heap.bb: ByteBuffer.put(byte[], int, int): " + (System.currentTimeMillis() - start));
=> heap.bb: ByteBuffer.put(byte[], int, int): 72
java.nio.ByteBuffer#put(java.nio.ByteBuffer)
dst.put(src);
System.out.println("heap.bb: ByteBuffer.put(java.nio.ByteBuffer): " + (System.currentTimeMillis() - start));
=> heap.bb: ByteBuffer.put(java.nio.ByteBuffer): 70
java.nio.ByteBuffer#put(byte) with loop
for (int i = 0; i < src.remaining(); i++) dst.put(src.get()); System.out.println("heap.bb: ByteBuffer.put(byte): " + (System.currentTimeMillis() - start));
Off heap上のByteBufferをコピー
java.nio.ByteBuffer#put(byte[], int, int)
ByteBuffer src = ByteBuffer.allocateDirect(256 * 1024 * 1024); ByteBuffer dst = ByteBuffer.allocate(256 * 1024 * 1024); long start = System.currentTimeMillis(); dst.put(src.array(), 0, src.remaining()); System.out.println("off-heap.bb: ByteBuffer.put(byte[], int, int): " + (System.currentTimeMillis() - start));
=> java.lang.UnsupportedOperationException (it doesn't have array inside)
java.nio.ByteBuffer#put(java.nio.ByteBuffer)
dst.put(src);
System.out.println("off-heap.bb: ByteBuffer.put(java.nio.ByteBuffer): " + (System.currentTimeMillis() - start));
=> off-heap.bb: ByteBuffer.put(java.nio.ByteBuffer): 72
java.nio.ByteBuffer#put(byte) with loop
for (int i = 0; i < src.remaining(); i++) dst.put(src.get()); System.out.println("off-heap.bb: ByteBuffer.put(byte): " + (System.currentTimeMillis() - start));
=> off-heap.bb: ByteBuffer.put(byte): 358