Skip to content

Commit

Permalink
perf: hoist variables which are not mutated or reassigned
Browse files Browse the repository at this point in the history
  • Loading branch information
benmccann committed Dec 27, 2023
1 parent 6307a33 commit be626e1
Show file tree
Hide file tree
Showing 6 changed files with 62 additions and 2 deletions.
5 changes: 5 additions & 0 deletions .changeset/twelve-peaches-jam.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'svelte': patch
---

perf: hoist variables which are not mutated or reassigned
Original file line number Diff line number Diff line change
Expand Up @@ -151,13 +151,27 @@ 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 || rune === '$effect.active' || rune === '$effect.root' || rune === '$inspect') {

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);
if (is_top_level && binding && !binding.mutated && !binding.reassigned) {
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);
state.hoisted.push(
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { test } from '../../test';

export default test({});
Original file line number Diff line number Diff line change
@@ -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();
}
Original file line number Diff line number Diff line change
@@ -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();
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<svelte:options runes={true} />

<script>
let count = 0;
</script>

<p>{count}</p>

0 comments on commit be626e1

Please sign in to comment.