Don't Use Spread Operator with Byte Arrays in JavaScript

Prapattimynk

Owner
Staff member
Joined
Feb 13, 2025
Messages
87

đźš« 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:
➡️ Benchmark Gist by slavafomin

âś… 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);

🔍 It's slightly more verbose, but **blazing fast**!

đź§  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
);

📌 Pro Tip: Use tinybench — a modern and accurate JS benchmarking tool to validate performance claims.


🌟 Extra Tips from Me:​


✅ Avoid `Array.prototype.concat` with large arrays for the same reason — it causes high memory churn and GC pauses.
✅ Use TypedArrays when working with binary data or crypto libraries — they’re leaner and optimized for performance.
✅ Benchmark your real-world scenarios — not just synthetic examples. Context matters!

🔥 Want more performance tips like this for Node.js, Rust, or WebAssembly? Stay tuned & subscribe to the thread!

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