- Joined
- Feb 13, 2025
- Messages
- 87
- Thread Author
- #1
Don't Use Spread Operator with Byte Arrays in JavaScript
Many devs (including experienced ones) unknowingly kill performance when handling byte arrays like this:
JavaScript:
// ❌ Bad Practice
const bytes1 = randomBytes(500);
const bytes2 = randomBytes(300);
const bytes3 = randomBytes(200);
const result = new Uint8Array([
...bytes1,
...bytes2,
...bytes3,
]);
Looks clean, right? But this is **10x–100x slower** than a proper approach. See this benchmark:

Optimal Way (High-Performance)
JavaScript:
const result = new Uint8Array(
bytes1.length +
bytes2.length +
bytes3.length
);
result.set(bytes1, 0);
result.set(bytes2, bytes1.length);
result.set(bytes3, bytes1.length + bytes2.length);

Bonus: Cleaner Abstraction
Use a writer utility to make it cleaner & maintainable:
JavaScript:
const writer = new BytesWriter({ size: totalSize });
const result = (writer
.writeBytes(bytes1)
.writeBytes(bytes2)
.writeBytes(bytes3)
.bytes
);

Extra Tips from Me:




#JavaScript #Performance #TypedArrays #WebDev #Nodejs #ByteHandling #Optimization #tinybench