0 day streak
javascript / expert
Snippet

High-Performance Memory Views via Subarrays

The subarray method on TypedArrays creates a new view on the existing buffer without allocating new memory for the data. This is critical for high-performance binary protocol parsing and reducing garbage collection pressure in Node.js applications.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
const largeBuffer = new Uint8Array(2048);
// Fill buffer with data...
// Create a view without copying memory
const headerView = largeBuffer.subarray(0, 16);
const payloadView = largeBuffer.subarray(16, 128);
payloadView[0] = 0xFF; // Modifies largeBuffer directly
console.log(largeBuffer[16]); // 255
nodejs
Breakdown
1
subarray(0, 16)
Returns a new TypedArray that points to the same underlying ArrayBuffer.
2
payloadView[0] = 0xFF
Directly affects the original buffer because memory is shared.