gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 12:44:36 24 4
gpt4 key购买 nike

我的代码是:

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() 不会抛出异常并返回一个带有数据的字节[]

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)); <----- HERE
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.

这是性能的低级内容。

根据这位研究人员的说法,这对最近的 Intel cpu 来说太过分了。在这里阅读更多:https://lemire.me/blog/2012/05/31/data-alignment-for-speed-myth-or-reality/

关于java - 为什么 DirectByteBuffer.array() 有额外的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50578070/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com