perf: hoist variables which are not mutated or reassigned

hoist-unmodified-var
Ben McCann 8 months ago
parent 6307a3322c
commit e0af98ba51

@ -0,0 +1,5 @@
---
'svelte': patch
---
perf: hoist variables which are not mutated or reassigned

@ -151,12 +151,30 @@ export const javascript_visitors_runes = {
return { ...node, body };
},
VariableDeclaration(node, { state, visit }) {
VariableDeclaration(node, { path, state, visit }) {
const declarations = [];
for (const declarator of node.declarations) {
const init = unwrap_ts_expression(declarator.init);
const rune = get_rune(init, state.scope);
if (!rune && init != null && declarator.id.type === 'Identifier') {
const is_top_level = path.at(-1)?.type === 'Program';
const binding = state.scope.owner(declarator.id.name)?.declarations.get(declarator.id.name);
// TODO: allow object expressions that are not passed to functions or components as props
// and expressions as long as they do not reference non-hoistable variables
if (
is_top_level &&
binding &&
!binding.mutated &&
!binding.reassigned &&
binding?.initial?.type === 'Literal'
) {
state.hoisted.push(b.declaration('const', declarator.id, init));
continue;
}
}
if (!rune || rune === '$effect.active' || rune === '$effect.root' || rune === '$inspect') {
if (init != null && is_hoistable_function(init)) {
const hoistable_function = visit(init);

@ -0,0 +1,3 @@
import { test } from '../../test';
export default test({});

@ -0,0 +1,19 @@
// index.svelte (Svelte VERSION)
// Note: compiler output will change before 5.0 is released!
import "svelte/internal/disclose-version";
import * as $ from "svelte/internal";
const count = 0;
var frag = $.template(`<p> </p>`);
export default function Hoist_unmodified_var($$anchor, $$props) {
$.push($$props, true);
/* Init */
var p = $.open($$anchor, true, frag);
var text = $.child(p);
text.nodeValue = $.stringify(count);
$.close($$anchor, p);
$.pop();
}

@ -0,0 +1,12 @@
// index.svelte (Svelte VERSION)
// Note: compiler output will change before 5.0 is released!
import * as $ from "svelte/internal/server";
export default function Hoist_unmodified_var($$payload, $$props) {
$.push(true);
let count = 0;
$$payload.out += `<p>${$.escape_text(count)}</p>`;
$.pop();
}

@ -0,0 +1,7 @@
<svelte:options runes={true} />
<script>
let count = 0;
</script>
<p>{count}</p>
Loading…
Cancel
Save