What excactly is a FloatBuffer?

Before you spam “its a thing you need to send data to openGL” i know that.

a direct floatbuffer apparently speeds up native function calls, why? What is the difference between a float[] and a FloatBuffer under the hood?

also, I did a test in filling float[10000000]s and float buffers using different methods.

doing


for(int i = 0; i < 10000000; i++)
{
array[i] = .5f;
}

took 47 ms

System.arraycopy took >1 ms

FloatBuffer.put(float[]) took 15ms
FloatBuffer.put(FloatBuffer) took 15ms

[edit]
re-did test with an array that is 10x as big, made the time diff more noticible

FloatBuffers allow better access from native code.

thanks, but the question is a little deeper than that. How does a FloatBuffer allow for better access by native than a float[]?

This is pure speculation from my part.

In Java, float[] points to a reference generated by bytecode. Since you can use float[].length, it probably makes float[] a class rather than an actual float array.

So, a FloatBuffer generates a memory location where it’s an actual byte array generated by bytecode. If anything were to read that FloatBuffer, it reads the byte array as a float array.

As tom_mai mentioned, a float[] is subject to the JVM’s whim, it might be compacted, fragmented, or moved by the JVM or garbage collector. This means that an OpenGL driver might obtain a pointer to the array, queue a command involving the array, but then when it goes to execute the command and do something with the array, the array may have moved causing the pointer to point to an invalid memory location.

A native buffer with the correct ByteOrder, will store its contents in a fixed location in memory in the correct endian-ness of the host machine. This allows the OS or drivers to receiver pointers to buffers and use them in the future because the location pointed to will always remain valid and will not be modified by the JVM or garbage collector.

That’s my understanding after doing some research.

Try reading the JavaDoc, it’s what it’s there for! :wink: http://docs.oracle.com/javase/7/docs/api/java/nio/ByteBuffer.html#direct

Essentially, a direct buffer exists (or behaves as such) outside the main Java memory heap, and in a consistent memory location. This makes it possible for native code to read/write to the buffer without extra copying overhead. (There are ways of pinning array memory for native calls (JNA does this) but it’s much more limiting).

Ok, that makes sense, thanks guys :slight_smile: