java bytebuffer 大小_java – 为什么DirectByteBuffer.array()有额外的大小?

我的代码是:

if (frameRGBABuffer == null) {

frameRGBABuffer = ByteBuffer.allocateDirect(cameraHeight * cameraWidth * 4)

.order(ByteOrder.nativeOrder());

}

Log.d("tag",frameRGBABuffer.array().length)

我的相机分辨率是1280×720,因此frameRGBABuffer应该分配3686400字节的空间.

但是很奇怪frameRGBABuffer.array()的长度是3686407.为什么它有额外的7个字节空格?

顺便说一下,frameRGBABuffer.array()不会抛出异常并返回带有数据的byte []

似乎Android分配了7个额外的空间来处理对齐.

源代码是:

MemoryRef(int capacity) {

VMRuntime runtime = VMRuntime.getRuntime();

buffer = (byte[]) runtime.newNonMovableArray(byte.class, capacity + 7);

allocatedAddress = runtime.addressOf(buffer);

// Offset is set to handle the alignment: http://b/16449607

offset = (int) (((allocatedAddress + 7) & ~(long) 7) - allocatedAddress);

isAccessible = true;

isFreed = false;

}

解决方法:

这是它背后的代码(JVM,不是Android,但在Android上可能类似):

DirectByteBuffer(int cap) { // package-private

super(-1, 0, cap, cap);

boolean pa = VM.isDirectMemoryPageAligned();

int ps = Bits.pageSize();

long size = Math.max(1L, (long)cap + (pa ? ps : 0));

Bits.reserveMemory(size, cap);

long base = 0;

try {

base = unsafe.allocateMemory(size);

} catch (OutOfMemoryError x) {

Bits.unreserveMemory(size, cap);

throw x;

}

unsafe.setMemory(base, size, (byte) 0);

if (pa && (base % ps != 0)) {

// Round up to page boundary

address = base + ps - (base & (ps - 1));

} else {

address = base;

}

cleaner = Cleaner.create(this, new Deallocator(base, size, cap));

att = null;

VM.isDirectMemoryPageAligned()< ---是关键

// User-controllable flag that determines if direct buffers should be page

// aligned. The "-XX:+PageAlignDirectMemory" option can be used to force

// buffers, allocated by ByteBuffer.allocateDirect, to be page aligned.

这是性能低级的东西.

标签:bytebuffer,android,java

来源: https://codeday.me/bug/20190828/1747249.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值