Page Speed Optimization

Transfer worker buffers without losing ownership of your data

Audit worker messages, detached buffers and the journey back to a visible result.

Two outlined browser work areas connected by a teal arrow, with one mint data card moving to the receiving area and an empty outlined slot left behind.

Moving computation into a worker does not automatically remove the cost of sending its input. Audit who owns each binary buffer before replacing a copy with a transfer, then measure the complete path back to a usable result.

Start with one expensive message

Choose one feature that already sends binary data to a dedicated worker, such as a local file preview or an image analysis tool. Keep the first investigation small: one input, one request and one visible result. Record the input size, the operation and the browser used. A worker receiving ordinary objects needs a different investigation from one receiving a large ArrayBuffer.

Capture a performance trace while running that feature. Look for preparation before postMessage(), the receiving worker's computation, the return message and the main thread's presentation work. If preparing the input dominates, changing the transfer list will leave that work in place. If building the result view dominates, the worker may already be doing its part successfully.

Use the JavaScript execution audit to identify the expensive stage before changing its transport. Do not infer a saving from the presence of a worker track alone. Write down what improvement would matter for this feature: a responsive cancel button, a shorter wait for the preview or lower memory pressure during repeated use.

Draw the ownership boundary

An ordinary worker message uses structured cloning for supported data. Transferring an ArrayBuffer instead moves ownership of its backing memory to the receiver and detaches the sender's buffer. The typed array that describes those bytes can be included in the message, but the transfer list contains its underlying buffer. Review the MDN explanation of transferable resources before changing an existing message contract.

For the audit, list every place that still expects to read the input after dispatch. The preview, an undo feature, a retry handler and an analytics callback might all hold references. Mark whether each needs the original bytes or only small metadata, such as the input's length and request identifier. Capture that metadata before transferring ownership.

Pay particular attention to multiple typed-array views over the same buffer. Their different variable names do not create independent storage. Transferring the backing buffer affects all those views in the sending context. A subarray is also a view, so transferring its buffer moves the underlying allocation, not just the selected range. If only that range should leave, first create a separate allocation and include the copying cost in the comparison.

Keep the payload and transfer list together

The transfer list controls ownership; it does not replace the message payload. A buffer listed for transfer must also be reachable by the receiving code through the message. Putting an otherwise unreferenced buffer in the list can detach it without giving the worker a useful reference to it. Review these two arguments together during code review.

This minimal example transfers four illustrative bytes and returns a small checksum. The values demonstrate the contract, not a performance result. Run the two scripts in a same-origin test page; the worker script is a separate file.

js
// main.js
const worker = new Worker("audit-worker.js");
const bytes = new Uint8Array([3, 5, 7, 9]);
worker.onmessage = ({ data }) => console.log(data);
worker.postMessage({ id: "audit-1", bytes }, [bytes.buffer]);
console.log(bytes.byteLength); // 0 after transfer

// audit-worker.js
self.onmessage = ({ data }) => {
  const checksum = data.bytes.reduce((sum, value) => sum + value, 0);
  self.postMessage({ id: data.id, checksum });
};

After successful transfer, the sender must stop treating bytes as readable input. Receiving the checksum does not restore that buffer. If the real workflow needs ownership back, design an explicit return transfer and use the newly received reference. Do not keep a detached reference in application state and expect a later message to repair it.

Choose a policy for each buffer

Copying is sometimes the correct choice. For example, a comparison view may intentionally keep the original while a worker modifies its own version. That is a different contract from handing a disposable input to a worker. Document the need first, then choose the transport that preserves it.

Requirement Candidate policy Check before adoption
Sender no longer needs input Transfer its buffer No remaining sender reads
Sender and worker need independent bytes Clone or make an explicit copy Extra allocation is acceptable
Only a small range is needed Copy that range into separate storage Copy cost and privacy boundary
Same storage moves through repeated stages Transfer ownership between stages Each stage uses the received reference

Keep this table with the feature's design notes. It makes accidental changes easier to spot: a future undo button can invalidate a previously safe transfer. Conversely, removing an unused preview may remove the last reason to retain a full input copy. Review the policy again when either feature changes.

Do not switch to shared memory merely to avoid deciding who owns the input. Shared memory introduces a separate concurrency design and security prerequisites. It is outside this audit. A straightforward ownership handoff is easier to test when the operation has a clear start and finish.

Measure the complete journey

Compare a clone version and a transfer version with identical useful work. Use equivalent fresh input for every run, because a buffer transferred in one run cannot be reused by the sender in the next. Keep input size, browser, device, worker lifecycle and output rendering constant. Include both the first use and subsequent uses as separate groups.

Workers have startup and memory costs, so spawning a new worker for every small request can obscure the transport comparison. Test the lifecycle the product actually uses. If you intend to reuse a worker, measure that design directly rather than presenting a warm worker result as the cost of the first visit.

Add named performance marks on the main thread before preparation, immediately before dispatch and when the matching reply arrives. Use measures between those marks to separate preparation from the round trip. Mark the worker's computation locally and report its duration as a separate value. Avoid subtracting raw timestamps from different contexts without accounting for their time origins.

The reply mark still does not prove that the user can see the result. Inspect the trace through the subsequent DOM update and rendering. Record end-to-end waiting and main-thread responsiveness alongside the local computation duration. The INP diagnosis guide helps distinguish event handling from the rendering work that follows it.

Repeat the comparison across representative input sizes and devices, keeping the raw observations. Report a distribution or range instead of selecting the quickest run. Do not describe the checksum demonstration as a benchmark. Its four bytes deliberately reveal ownership behavior without suggesting that such a small message needs optimization.

Bound pending work and stale replies

A fast handoff does not make an unlimited queue useful. If a visitor changes an input repeatedly, the worker may finish requests that the interface no longer needs. Give each request an identifier, track the currently relevant one and reject obsolete replies before updating the page. Keep a separate count of pending operations so discarded results do not hide growing work.

For an interactive preview, consider allowing one operation in flight and retaining only the latest requested input until it finishes. That is a product policy, not a requirement of postMessage(). Test whether it matches the feature: a batch export may need every item, while a slider preview may need only its latest state. Never silently drop jobs that the user expects to complete.

Decide what cancellation means for transferred input. Stopping a worker does not hand its owned buffer back to the page. A retry therefore needs a retained source that can recreate the input, or an explicit recovery protocol that completes before termination. Verify that recovery path with a realistic file rather than only the small demonstration array.

Finish with correctness evidence

Test normal completion, rapid repeated requests, navigation away, worker failure and cancellation. Check that the visible result belongs to the current input and that no sender code tries to consume detached storage. Exercise any alternate views over the buffer, including a view that represents only part of a larger allocation.

Inspect repeated use for accumulating workers, event listeners and pending requests. Log identifiers, sizes and timings rather than users' file contents. Keep failure messages actionable without exposing the underlying data. The audit should leave a maintainer able to tell whether a job failed during preparation, dispatch, computation or presentation.

Ship the transfer version only when it preserves the feature's behavior and improves the measured bottleneck on relevant devices. Retain the comparison conditions, ownership table and rollback path with the change. The useful outcome is a smaller, explicit data contract whose performance can be reproduced, with every remaining copy serving a documented purpose.

Related guides