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?

Newbyte
  • 2,421
  • 5
  • 22
  • 45

2 Answers2

1

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.

httpdigest
  • 5,411
  • 2
  • 14
  • 28
0

I would recommend using a float[] instead of a FloatBuffer because a float[] seems to work more, and it's exactly what you expect: an array of bytes on the stack. Also, behind the scenes, a FloatBuffer is really just a float[] so it doesnt matter TOO much at the end of the day. To continue off my point, converting a float[] to a FloatBuffer seems unnecessary and overly complicated.

Dharman
  • 30,962
  • 25
  • 85
  • 135