DNAが言及しているように、事前に充填されたバッファーを用意して使用するByteBuffer.put(ByteBuffer)
のが、おそらく最速のポータブルな方法です。Arrays.fill
それが実用的でない場合は、次のいずれかを利用するために、またはUnsafe.putLong
該当する場合は、次のようなことを行うことができます。
public static void fill(ByteBuffer buf, byte b) {
if (buf.hasArray()) {
final int offset = buf.arrayOffset();
Arrays.fill(buf.array(), offset + buf.position(), offset + buf.limit(), b);
buf.position(buf.limit());
} else {
int remaining = buf.remaining();
if (UNALIGNED_ACCESS) {
final int i = (b << 24) | (b << 16) | (b << 8) | b;
final long l = ((long) i << 32) | i;
while (remaining >= 8) {
buf.putLong(l);
remaining -= 8;
}
}
while (remaining-- > 0) {
buf.put(b);
}
}
}
設定UNALIGNED_ACCESS
には、JREの実装とプラットフォームに関するある程度の知識が必要です。JNA(システムプロパティPlatform.ARCH
にアクセスするための便利で標準的な方法として提供されます)も使用する場合に、OracleJRE用に設定する方法は次のとおりです。os.arch
/**
* Indicates whether the ByteBuffer implementation likely supports unaligned
* access of multi-byte values on the current platform.
*/
private static final boolean UNALIGNED_ACCESS = Platform.ARCH.startsWith("x86");