From 23b9b7dcd39bb68925d9a5015ce8a7e2a11fc881 Mon Sep 17 00:00:00 2001 From: Chris Duncan Date: Thu, 12 Dec 2024 06:59:27 -0800 Subject: [PATCH] Add pool function to check if object should be transferred to the worker directly instead of encoding its JSON representation. --- src/lib/pool.ts | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/src/lib/pool.ts b/src/lib/pool.ts index 8799417..0ca7d97 100644 --- a/src/lib/pool.ts +++ b/src/lib/pool.ts @@ -48,6 +48,12 @@ export class Pool { job.data = job.data.slice(chunk) if (job.data.length === 0) this.#queue.shift() if (next?.length > 0) { + if (this.#isTransferable(next)) { + thread.worker.postMessage({ name: job.name, next }, [next]) + } + } else if (this.#isTransferable(next[0])) { + thread.worker.postMessage({ name: job.name, next }, next) + } else { const buffer = new TextEncoder().encode(JSON.stringify(next)).buffer thread.job = job thread.worker.postMessage({ name: job.name, buffer }, [buffer]) @@ -61,6 +67,25 @@ export class Pool { return true } + static #isTransferable (obj: any): boolean { + return obj instanceof ArrayBuffer + //@ts-expect-error + || obj instanceof AudioData + || obj instanceof ImageBitmap + || obj instanceof MediaSourceHandle + || obj instanceof MIDIAccess + || obj instanceof OffscreenCanvas + || obj instanceof ReadableStream + || obj instanceof RTCDataChannel + || obj instanceof TransformStream + || obj instanceof VideoFrame + //@ts-expect-error + || obj instanceof WebTransportReceiveStream + //@ts-expect-error + || obj instanceof WebTransportSendStream + || obj instanceof WritableStream + } + static #report (thread: Thread, results: any[]): void { if (thread.job == null) { throw new Error('Thread returned results but had nowhere to report it.') -- 2.34.1