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

Why does DirectByteBuffer.array() have extra size?

我的代码是:

if (frameRGBABuffer == null) {
    frameRGBABuffer = ByteBuffer.allocateDirect(cameraHeight * cameraWidth * 4)
        .order(ByteOrder.nativeOrder());
}

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

我的相机分辨率是1280×720,所以frameRGBABuffer应该分配3686400字节space。

但是奇怪的是frameRGBABuffer.array()的长度是3686407,为什么多了7个字节space?

顺便说一句,frameRGBABuffer.array() 没有抛出异常并且 returns 一个带有数据

的字节 []

似乎 Android 额外分配了 7 个 space 来处理对齐。 源代码是:

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.

这是性能的低级内容。

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