Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion benchmark/misc/structured-clone.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,19 @@ const common = require('../common.js');
const assert = require('assert');

const bench = common.createBenchmark(main, {
type: ['string', 'object', 'arraybuffer'],
type: ['primitive', 'string', 'object', 'arraybuffer'],

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instead of primitive, we can just use int, and we can eventually add BigInt/boolean as well.

n: [1e4],
});

function main({ n, type }) {
const data = [];

switch (type) {
case 'primitive':
for (let i = 0; i < n; ++i) {
data.push(i);
}
break;
case 'string':
for (let i = 0; i < n; ++i) {
data.push(new Date().toISOString());
Expand Down
11 changes: 11 additions & 0 deletions lib/internal/worker/js_transferable.js
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,17 @@ function structuredClone(value, options) {
throw new ERR_MISSING_ARGS('The value argument must be specified');
}

// Fast path: primitives clone to themselves, so skip the native
// serialize/deserialize round-trip when no options were provided.
// Symbols are excluded. they are not cloneable and must throw below.
if (options === undefined &&
(value === null ||
(typeof value !== 'object' &&
typeof value !== 'function' &&
typeof value !== 'symbol'))) {
return value;
}

const idlOptions = webidl.converters.StructuredSerializeOptions(
options,
{
Expand Down
11 changes: 11 additions & 0 deletions test/parallel/test-structuredClone-global.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,17 @@ assert.strictEqual(structuredClone(undefined, null), undefined);
// Transfer can be null or undefined.
assert.strictEqual(structuredClone(undefined, { }), undefined);

// Primitives clone to themselves.
assert.strictEqual(structuredClone(null), null);
assert.strictEqual(structuredClone(1), 1);
assert.strictEqual(structuredClone('x'), 'x');
assert.strictEqual(structuredClone(true), true);
assert.strictEqual(structuredClone(10n), 10n);
// -0 is preserved.
assert.ok(Object.is(structuredClone(-0), -0));
// Symbols are not cloneable and must throw.
assert.throws(() => structuredClone(Symbol()), { name: 'DataCloneError' });

// Transferables or its subclasses should be received with its closest transferable superclass
for (const StreamClass of [ReadableStream, WritableStream, TransformStream]) {
const original = new StreamClass();
Expand Down
Loading