Performance: SharedArrayBuffer for shared memory
This affects how efficiently multiple threads or workers share and access memory without copying data, improving concurrency and responsiveness.
Jump into concepts and practice - no test required
const { Worker, isMainThread, workerData } = require('worker_threads');
const sharedBuffer = new SharedArrayBuffer(1024);
if (isMainThread) {
const worker = new Worker('./worker.js', { workerData: sharedBuffer });
} else {
const shared = new Uint8Array(workerData);
// Access shared memory directly without copying
}const { Worker } = require('worker_threads');
const buffer = new ArrayBuffer(1024);
const worker = new Worker('./worker.js', { workerData: buffer });
// Worker copies the buffer, no real shared memory| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| ArrayBuffer passed to worker | N/A | N/A | N/A | [X] Bad |
| SharedArrayBuffer passed to worker | N/A | N/A | N/A | [OK] Good |
SharedArrayBuffer in Node.js?SharedArrayBuffer is designed to create a block of memory that can be shared between multiple threads or workers.SharedArrayBuffer.SharedArrayBuffer of 1024 bytes in Node.js?SharedArrayBuffer must be created with the new keyword and a size in bytes as argument.new SharedArrayBuffer(1024), which is correct. const sab = SharedArrayBuffer(1024); misses new. const sab = new SharedArrayBuffer(); misses size argument. const sab = SharedArrayBuffer.new(1024); uses invalid syntax.new with size in bytes [OK]const sab = new SharedArrayBuffer(4); const int32 = new Int32Array(sab); int32[0] = 10; Atomics.add(int32, 0, 5); console.log(int32[0]);
int32[0] is set to 10. Then Atomics.add adds 5 to this value atomically.int32[0] becomes 15.const sab = new SharedArrayBuffer(8); const uint8 = new Uint8Array(sab); uint8[0] = 255; Atomics.store(uint8, 0, 256); console.log(uint8[0]);
uint8[0] becomes 0, not 256.SharedArrayBuffer. Which code snippet correctly increments the counter without race conditions?
// Shared buffer and typed array
const sab = new SharedArrayBuffer(4);
const counter = new Int32Array(sab);
counter[0] = 0;
// Increment function
function increment() {
// Which line correctly increments?
}counter[0] with normal operators can cause race conditions when multiple threads run concurrently.Atomics.add(counter, 0, 1) safely increments the value at index 0 without conflicts.