Are the advantages of Typed Arrays in JavaScript is that they work the same or similar in C?

前端 未结 4 1313
囚心锁ツ
囚心锁ツ 2021-01-30 17:41

I\'ve been playing around with Typed Arrays in JavaScript.

var buffer = new ArrayBuffer(16);
var int32View = new Int32Array(buffer);

I imagine

4条回答
  •  既然无缘
    2021-01-30 18:28

    Yes, you are mostly correct. With a standard JavaScript array, the JavaScript engine has to assume that the data in the array is all objects. It can still store this as a C-like array/vector, where the access to the memory is still like you described. The problem is that the data is not the value, but something referencing that value (the object).

    So, performing a[i] = b[i] + 2 requires the engine to:

    1. access the object in b at index i;
    2. check what type the object is;
    3. extract the value out of the object;
    4. add 2 to the value;
    5. create a new object with the newly computed value from 4;
    6. assign the new object from step 5 into a at index i.

    With a typed array, the engine can:

    1. access the value in b at index i (including placing it in a CPU register);
    2. increment the value by 2;
    3. assign the new object from step 2 into a at index i.

    NOTE: These are not the exact steps a JavaScript engine will perform, as that depends on the code being compiled (including surrounding code) and the engine in question.

    This allows the resulting computations to be much more efficient. Also, the typed arrays have a memory layout guarantee (arrays of n-byte values) and can thus be used to directly interface with data (audio, video, etc.).

提交回复
热议问题