perf: optimize simple object destructuring in @const tags (#18390)

This PR resolves a `TODO` in `ConstTag.js` regarding the optimization of
simple object pattern matching cases like `{@const { x } = y}`.

---------

Co-authored-by: Simon H <5968653+dummdidumm@users.noreply.github.com>
pull/17306/merge
PD Shaheed Ali Khan 3 days ago committed by GitHub
parent a6560bbe08
commit 2ac7366391
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -0,0 +1,5 @@
---
"svelte": patch
---
perf: optimize simple object destructuring in `@const` tags

@ -59,7 +59,7 @@ export function parse(source, comments, typescript, is_script) {
return /** @type {Program} */ (ast);
} catch (err) {
// TODO the `return` in necessary for TS<7 due to a bug; otherwise
// TODO the `return` is necessary for TS<7 due to a bug; otherwise
// the `finally` block is regarded as unreachable
return handle_parse_error(err);
} finally {

@ -45,18 +45,29 @@ export function ConstTag(node, context) {
transform
});
// TODO optimise the simple `{ x } = y` case — we can just return `y`
// instead of destructuring it only to return a new object
const is_simple_object_pattern =
declaration.id.type === 'ObjectPattern' &&
declaration.id.properties.every(
(p) =>
p.type === 'Property' &&
!p.computed &&
p.key.type === 'Identifier' &&
p.value.type === 'Identifier' &&
p.key.name === p.value.name
);
const init = build_expression(
{ ...context, state: child_state },
declaration.init,
node.metadata.expression
);
const block = b.block([
b.const(/** @type {Pattern} */ (context.visit(declaration.id, child_state)), init),
b.return(b.object(identifiers.map((node) => b.prop('init', node, node))))
]);
const block = is_simple_object_pattern
? b.block([b.return(init)])
: b.block([
b.const(/** @type {Pattern} */ (context.visit(declaration.id, child_state)), init),
b.return(b.object(identifiers.map((node) => b.prop('init', node, node))))
]);
let expression = create_derived(context.state, block, node.metadata.expression.has_await);

Loading…
Cancel
Save