Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy TypedArray into another TypedArray?

C# has a high performance array copying function to copy arrays in place:

Array.Copy(source, destination, length)

It's faster than doing it manually ie.:

for (var i = 0; i < length; i++)
    destination[i] = source[i];

I am looking for an equivalent high performance copy function to copy arrays in place, for Int32Array and Float32Array in Javascript and can find no such function:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray

The closest is "copyWithin" which only does an copy internally within an array.

Is there a built in high performance copy function for TypedArrays in place?

Plan B, is there a built in high performance clone function instead? (EDIT: looks like slice() is the answer to that)

like image 903
Brendan Hill Avatar asked Feb 22 '16 20:02

Brendan Hill


People also ask

What is typed array?

A Typed Array is a slab of memory with a typed view into it, much like how arrays work in C. Because a Typed Array is backed by raw memory, the JavaScript engine can pass the memory directly to native libraries without having to painstakingly convert the data to a native representation.

What is the use of a Typedarray object in JavaScript?

JavaScript typed arrays are array-like objects that provide a mechanism for reading and writing raw binary data in memory buffers. Array objects grow and shrink dynamically and can have any JavaScript value. JavaScript engines perform optimizations so that these arrays are fast.

Why might you use typed arrays instead of standard arrays?

Normal arrays can be as fast as typed arrays if you do a lot of sequential access. Random access outside the bounds of the array causes the array to grow. Typed arrays are fast for access, but slow to be allocated. If you create temporary arrays frequently, avoid typed arrays.


1 Answers

You're looking for .set which allows you to set the values of an array using an input array (or TypedArray), optionally starting at some offset on the destination array:

destination.set(source);
destination.set(source, offset);

Or, to set a limited amount of the input array:

destination.set(source.slice(limit), offset);

If you instead want to create a new TypedArray, you can simply use .slice:

source.slice();
like image 185
apsillers Avatar answered Sep 22 '22 09:09

apsillers