Skip to content

Svelte 5: prop getters are invoked repeatedly #9751

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Rich-Harris opened this issue Dec 4, 2023 · 0 comments · Fixed by #9757
Closed

Svelte 5: prop getters are invoked repeatedly #9751

Rich-Harris opened this issue Dec 4, 2023 · 0 comments · Fixed by #9757
Assignees
Milestone

Comments

@Rich-Harris
Copy link
Member

Describe the bug

Code like this...

<script>
  import Child from './Child.svelte';
</script>

<Child random={Math.random().toFixed(2)} />

...generates code like this:

var fragment = $.comment($$anchor);
var node = $.child_frag(fragment);

Child(node, {
  get random() {
    return Math.random().toFixed(2);
  }
});

$.close_frag($$anchor, fragment);
$.pop();

This means that each random reference within Child will be different. It also means that we're computing stuff unnecessarily.

To solve this, we probably need to use a derived source...

var fragment = $.comment($$anchor);
var node = $.child_frag(fragment);

{
  const random = $.derived(() => Math.random().toFixed(2));

  Child(node, {
    get random() {
      return $.get(random);
    }
  });
}

$.close_frag($$anchor, fragment);
$.pop();

...though in some cases (including this one) we could presumably detect via static analysis that no signals are used, and that we can do this instead:

var fragment = $.comment($$anchor);
var node = $.child_frag(fragment);

Child(node, {
  random: Math.random().toFixed(2)
});

$.close_frag($$anchor, fragment);
$.pop();

Reproduction

https://svelte-5-preview.vercel.app/#H4sIAAAAAAAAE42OywqDMBBFfyWEggoSoUurQil01y-oXYiJGDDJkIylJeTf66O0Cxft8lzmzj2ednIQjuZXT3WjBM3pEYCmFJ8wg7uLAcXEzoy2nZPCtVYCVrWuUSowFsmplwMnnTWKRCxbiK3F6FDrIvs2dLHe2kZzo0p_abBnK8QJQ3OWD8HjfRJIVk2jynDZScFpjnYUIf04Ll_-tRwEEv-eJIGUZAfWgIuTjRxUfj0LRQbV72CreAsvyJ0MP1IBAAA=

Logs

No response

System Info

next

Severity

blocking an upgrade

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants