为什么使用 FloatBuffer 而不是 float[]?
我已经在我的 Android 代码中使用 FloatBuffers 有一段时间了(从一些 opengles 教程中复制了它),但我无法准确理解这个构造是什么以及为什么需要它.
I've been using FloatBuffers in my Android code for a while (copied it from some opengles tutorial), but I cannot understand exactly what this construct is and why it is needed.
例如,我在很多人的代码和 android 教程中看到的这段代码(或类似代码):
For example this code (or similar) I see in many many peoples' code and android tutorials:
float[] vertices = ...some array...
ByteBuffer vbb = ByteBuffer.allocateDirect(vertices.length * 4);
vbb.order(ByteOrder.nativeOrder()); // use the device hardware's native byte order
FloatBuffer fb = vbb.asFloatBuffer(); // create a floating point buffer from the ByteBuffer
fb.put(vertices); // add the coordinates to the FloatBuffer
fb.position(0); // set the buffer to read the first coordinate
这似乎非常冗长和混乱,据我所知,这只是一个花哨的浮点数组的包装.
This seems awfully verbose and messy for something which as far as I can tell is just a fancy wrapper around of an array of floats.
问题:
与任何其他类型的集合或简单的浮点数组相比,这种类型的类(ByteBuffer、FloatBuffer)的理由是什么?
What is the justification for this type of class (ByteBuffer, FloatBuffer), as opposed to any other kind of collection or simple array of floats?
在将 ByteBuffer 转换为 FloatBuffer 之前创建它的想法是什么?
What's the idea behind creating a ByteBuffer before converting it into a FloatBuffer?
推荐答案
主要原因是性能:ByteBuffers 和其他 NIO 类在与本机代码交互时启用加速操作(通常是通过避免将数据复制到临时缓冲区).
The main reason is performance: ByteBuffers and the other NIO classes enable accelerated operations when interfacing with native code (typically by avoiding the need to copy data into a temporary buffer).
例如,如果您正在执行大量 OpenGL 渲染调用,这一点非常重要.
This is pretty important if you are doing a lot of OpenGL rendering calls for example.
首先创建一个 ByteBuffer 的原因是您想使用 allocateDirect 调用来创建一个 direct 字节缓冲区,这得益于加速操作.然后,您可以从中创建一个共享相同内存的 FloatBuffer.由于某种原因,FloatBuffer 本身没有 allocateDirect 方法,这就是您必须通过 ByteBuffer 的原因.
The reason for creating a ByteBuffer first is that you want to use the allocateDirect call to create a direct byte buffer, which benefits from the accelerated operations. You then create a FloatBuffer from this that shares the same memory. The FloatBuffer doesn't itself have an allocateDirect method for some reason, which is why you have to go via ByteBuffer.
相关文章