Search code examples
javaopenglbufferlwjglfloatbuffer

Is there any difference between giving GL15.glBufferData() a float array or a FloatBuffer in LWJGL 3.0?


I was recently watching a tutorial on writing an OpenGL game in Java with LWJGL. In it, the narrator/author first converts the float array from float[] to a FloatBuffer before giving it toGL15.glBufferData(). Initially I didn't think much of this, but I accidentally gave GL15.glBufferData() the float array directly instead of converting it to a FloatBuffer, and the code ended up working anyway. I looked up the documentation and it only says "Array version of: BufferData" as comment, which still leaves me uncertain.

This leads me to wonder, is there any point of going through the effort to convert float[] to a FloatBuffer when calling GL15.glBufferData() in LWJGL 3.0 with Java 15, assuming the FloatBuffer was given its value by using FloatBuffer::put() and thus contains the same data?


Solution

  • The difference between a direct NIO Buffer and a float array is that when you hand a float array to LWJGL, it will first need to pin the array using a JNI call into the Java runtime, which will give LWJGL's native code a virtual memory address it can hand over to the actual called native function. Then, the float array needs to be unpinned again, making it eligible again for garbage collection.

    With a direct NIO Buffer, this does not need to happen, because direct NIO Buffers are already backed by a native virtual memory address. So using direct NIO Buffers is considerably faster (performance-wise). Of course, all this performance is somewhat lost when you first create a float array and then copy it into the NIO Buffer.

    You are expected to simply not use a float array to being with, but only ever populate your direct NIO Buffer.