Skip to content

Commit

Permalink
perf: improve list sync on remove case
Browse files Browse the repository at this point in the history
  • Loading branch information
lifeart committed Dec 27, 2023
1 parent ab04b99 commit b0821b0
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 8 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
20 changes: 14 additions & 6 deletions benchmark/benchmarks/krausest/lib/components/list.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,23 @@ 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
const removedIndexes = keysToRemove.map((key) => this.destroyListItem(key));
for (const value of this.keyMap.values()) {
removedIndexes.forEach((index) => {
if (value.index > index) {
value.index--;
}
});
}

items.forEach((item, index) => {
if (seenKeys === amountOfKeys && !(targetNode instanceof DocumentFragment)) {
// optimization for appending items case
Expand All @@ -46,16 +59,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,7 +92,7 @@ export class ListComponent {
row.nodes.forEach((node) => {
node.parentElement?.removeChild(node);
});
return this;
return row.index;
}
}

Expand Down

0 comments on commit b0821b0

Please sign in to comment.