Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/tidy-months-rush.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'svelte': patch
---

fix: don't run each array expression more often than necessary
13 changes: 9 additions & 4 deletions packages/svelte/src/internal/client/dom/blocks/each.js
Original file line number Diff line number Diff line change
Expand Up @@ -136,15 +136,17 @@ export function each(node, flags, get_collection, get_key, render_fn, fallback_f

var was_empty = false;

// TODO: ideally we could use derived for runes mode but because of the ability
// to use a store which can be mutated, we can't do that here as mutating a store
// will still result in the collection array being the same from the store
// We wrap this in a derived to ensure possible effects created as a result are associated with the derived,
// rather than the each effect. Because people can mutate arrays and trigger reactivity through other means still,
// we need to use derived_safe_equal.
var each_array = derived_safe_equal(() => {
var collection = get_collection();

return is_array(collection) ? collection : collection == null ? [] : array_from(collection);
});

var first_run = true;

block(() => {
var array = get(each_array);
var length = array.length;
Expand Down Expand Up @@ -257,7 +259,10 @@ export function each(node, flags, get_collection, get_key, render_fn, fallback_f
// that a mutation occurred and it's made the collection MAYBE_DIRTY, so reading the
// collection again can provide consistency to the reactive graph again as the deriveds
// will now be `CLEAN`.
get(each_array);
if (first_run) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wonder if it's only first run. Like if you run a conditional collection that changes deps between runs, is that also a problem?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's a shame we use derived_safe_equal otherwise this wouldn't be an issue.

first_run = false;
get(each_array);
}
});

if (hydrating) {
Expand Down
Loading