Why is copying a Uint8Array to a Uint8ClampedArray slower than copying a Uint8Array to a new Uint8Array?

Viewed 219

It appears that copying a Uint8Array into a Uint8ClampedArray is much slower than cloning the Uint8Array and using its underlying 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).

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.

Firefox gives similar stats (140ms vs 60ms), while Safari shows more extreme differences (550ms vs 30ms).

1 Answers

I'm not seeing those time differences in browser or in 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
Related