How to copy TypedArray into another TypedArray?

穿精又带淫゛_ 提交于 2020-11-29 04:16:18

问题


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)


回答1:


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();



回答2:


You can clone an array using slice(0);.

var clone = myArray.slice(0);

And you can make it a native method:

Array.prototype.clone = function() {
    return this.slice(0);
};

Performance link comparing to loop




回答3:


clone to an exist typedarray:

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

clone to a new typedarray example: (It's fastest!)

var source = new Uint8Array([1,2,3]);
var cloned = new Uint8Array(source);


来源:https://stackoverflow.com/questions/35563529/how-to-copy-typedarray-into-another-typedarray

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!