問題描述
我已經在我的 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.
這篇關于為什么使用 FloatBuffer 而不是 float[]?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!