简体   繁体   English

为什么将 Uint8Array 复制到 Uint8ClampedArray 比将 Uint8Array 复制到新的 Uint8Array 慢?

[英]Why is copying a Uint8Array to a Uint8ClampedArray slower than copying a Uint8Array to a new Uint8Array?

It appears that copying a Uint8Array into a Uint8ClampedArray is much slower than cloning the Uint8Array and using its underlying ArrayBuffer :似乎将Uint8Array复制到Uint8ClampedArray比克隆Uint8Array并使用其底层ArrayBuffer慢得多:

 const foo = new Uint8Array(0x10000000); // 256MiB console.time('Copy into Uint8ClampedArray'); const bar = new Uint8ClampedArray(foo); console.timeEnd('Copy into Uint8ClampedArray');

The code above clocks at ~160ms on my machine (Chrome v96, MacBook Pro).上面的代码在我的机器(Chrome v96、MacBook Pro)上的时钟频率约为 160 毫秒。

 const foo = new Uint8Array(0x10000000); // 256MiB console.time('Clone, then use ArrayBuffer'); const bar = new Uint8ClampedArray(new Uint8Array(foo).buffer); console.timeEnd('Clone, then use ArrayBuffer');

The code above clocks at ~70ms on my machine.上面的代码在我的机器上以大约 70 毫秒的速度运行。

Firefox gives similar stats (140ms vs 60ms), while Safari shows more extreme differences (550ms vs 30ms). Firefox 给出了类似的统计数据(140 毫秒对 60 毫秒),而 Safari 显示出更极端的差异(550 毫秒对 30 毫秒)。

Read the answer on this: JavaScript pre-allocated array Uncaught RangeError: Invalid Array Length阅读关于此的答案: JavaScript 预分配数组 Uncaught RangeError: Invalid Array Length

In your case, Uint8Array values stored in place, but Uint8ClampedArray values - stored in heap with a reference.在您的情况下, Uint8Array值存储在适当的位置,但Uint8ClampedArray值 - 存储在堆中并带有引用。 So object creation for each value takes some time.所以为每个值创建 object 需要一些时间。

I'm not seeing those time differences in browser or in NodeJs我没有在浏览器或 NodeJs 中看到这些时间差异

foo = new Uint8Array(256 * 1024**2); // 256MiB
console.time(label = 'Copy into Uint8ClampedArray');
bar = new Uint8ClampedArray(foo);
console.timeEnd(label);

foo = new Uint8Array(256 * 1024**2); // 256MiB
console.time(label = 'Clone, then use ArrayBuffer');
bar = new Uint8ClampedArray(new Uint8Array(foo).buffer);
console.timeEnd(label);
$ node -v && node test.js
v17.2.0
Copy into Uint8ClampedArray: 174.049ms
Clone, then use ArrayBuffer: 193.819ms

$ node -v && node test.js
v17.2.0
Copy into Uint8ClampedArray: 170.152ms
Clone, then use ArrayBuffer: 192.41ms

$ node -v && node test.js
v17.2.0
Copy into Uint8ClampedArray: 168.555ms
Clone, then use ArrayBuffer: 209.525ms

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM