When to use Array, Buffer or direct Buffer

前端 未结 2 982
梦毁少年i
梦毁少年i 2020-12-04 22:27

Question

While writing a Matrix class for use with OpenGL libraries, I came across the question of whether to use Java arrays or a Buffer strategy to store the dat

2条回答
  •  醉梦人生
    2020-12-04 22:59

    Direct buffers are not meant to accelerate access from Java code. (If that were possible there was something wrong with the JVM’s own array implementation.)

    These byte buffers are for interfacing with other components as you can write a byte buffer to a ByteChannel and you can use direct buffers in conjunction with native code such as with the OpenGL libraries you mentioned. It’s intended to accelerate these operation then. Using a graphics card’s chip for rendering can accelerate the overall operation to a degree more than compensating the possibly slower access to the buffer from Java code.

    By the way, if you measure the access speed to a byte buffer, especially the direct byte buffers, it’s worth changing the byte order to the native byte order before acquiring a FloatBuffer view:

    FloatBuffer bufferD = ByteBuffer.allocateDirect(SIZE * 4)
                                    .order(ByteOrder.nativeOrder())
                                    .asFloatBuffer();
    

提交回复
热议问题