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

时间:2018-05-29 06:54:35

标签: java android bytebuffer

我的代码是:

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;
}

1 个答案:

答案 0 :(得分:5)

这是它背后的代码(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()&lt; ---是关键

// 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.

这是性能低级的东西。

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