Skip to content

Svelte 5: prop getters are invoked repeatedly #9751

@Rich-Harris

Description

@Rich-Harris

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

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions