Skip to content

Commit

Permalink
perf: improve list sync
Browse files Browse the repository at this point in the history
perf: improve list sync
  • Loading branch information
lifeart committed Dec 27, 2023
1 parent ab04b99 commit 7df1cf5
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 7 deletions.
2 changes: 0 additions & 2 deletions benchmark/benchmarks/krausest/lib/components/Application.ts
Original file line number Diff line number Diff line change
Expand Up @@ -131,9 +131,7 @@ export class Application {
this.children.push(this.list);
}
removeItem(item: Item) {
const key = this.list.keyForItem(item);
this.items = this.items.filter((i) => i.id !== item.id);
this.list.destroyListItem(key);
}
create_1_000_Items() {
this.items = buildData(1000);
Expand Down
18 changes: 13 additions & 5 deletions benchmark/benchmarks/krausest/lib/components/list.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,18 @@ export class ListComponent {
}
syncList(items: Item[]) {
const existingKeys = new Set(this.keyMap.keys());
const updatingKeys = new Set(items.map((item) => this.keyForItem(item)));
const keysToRemove = [...existingKeys].filter((key) => !updatingKeys.has(key));
const amountOfKeys = existingKeys.size;
let targetNode = amountOfKeys > 0 ? this.parent : document.createDocumentFragment();
const rowsToMove: Array<[ReturnType<typeof RowComponent>, number]> = [];
let seenKeys = 0;

// iterate over existing keys and remove them
keysToRemove.forEach((key) => {
this.destroyListItem(key);
});

items.forEach((item, index) => {
if (seenKeys === amountOfKeys && !(targetNode instanceof DocumentFragment)) {
// optimization for appending items case
Expand All @@ -46,16 +54,11 @@ export class ListComponent {
this.keyMap.set(key, row);
} else {
seenKeys++;
existingKeys.delete(key);
if (maybeRow.index !== index) {
rowsToMove.push([maybeRow, index]);
}
}
});
// iterate over existing keys and remove them
existingKeys.forEach((key) => {
this.destroyListItem(key);
});
// iterate over rows to move and move them
rowsToMove.forEach(([row, index]) => {
const nextItem = items[index + 1];
Expand Down Expand Up @@ -84,6 +87,11 @@ export class ListComponent {
row.nodes.forEach((node) => {
node.parentElement?.removeChild(node);
});
for (const value of this.keyMap.values()) {
if (value.index > row.index) {
value.index--;
}
}
return this;
}
}
Expand Down

0 comments on commit 7df1cf5

Please sign in to comment.