Skip to content

Commit ad33e9e

Browse files
authored
fix performance regression when introducing truncate (#430)
1 parent da89efb commit ad33e9e

File tree

2 files changed

+14
-3
lines changed

2 files changed

+14
-3
lines changed

.changeset/cuddly-hands-lose.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@tanstack/db": patch
3+
---
4+
5+
fix for a performance regression when syncing large collections due to a look up of previously deleted keys

packages/db/src/collection.ts

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,7 @@ interface PendingSyncedTransaction<T extends object = Record<string, unknown>> {
6666
committed: boolean
6767
operations: Array<OptimisticChangeMessage<T>>
6868
truncate?: boolean
69+
deletedKeys: Set<string | number>
6970
}
7071

7172
/**
@@ -542,6 +543,7 @@ export class CollectionImpl<
542543
this.pendingSyncedTransactions.push({
543544
committed: false,
544545
operations: [],
546+
deletedKeys: new Set(),
545547
})
546548
},
547549
write: (messageWithoutKey: Omit<ChangeMessage<T>, `key`>) => {
@@ -560,9 +562,8 @@ export class CollectionImpl<
560562
// Check if an item with this key already exists when inserting
561563
if (messageWithoutKey.type === `insert`) {
562564
const insertingIntoExistingSynced = this.syncedData.has(key)
563-
const hasPendingDeleteForKey = pendingTransaction.operations.some(
564-
(op) => op.key === key && op.type === `delete`
565-
)
565+
const hasPendingDeleteForKey =
566+
pendingTransaction.deletedKeys.has(key)
566567
const isTruncateTransaction = pendingTransaction.truncate === true
567568
// Allow insert after truncate in the same transaction even if it existed in syncedData
568569
if (
@@ -579,6 +580,10 @@ export class CollectionImpl<
579580
key,
580581
}
581582
pendingTransaction.operations.push(message)
583+
584+
if (messageWithoutKey.type === `delete`) {
585+
pendingTransaction.deletedKeys.add(key)
586+
}
582587
},
583588
commit: () => {
584589
const pendingTransaction =
@@ -619,6 +624,7 @@ export class CollectionImpl<
619624

620625
// Clear all operations from the current transaction
621626
pendingTransaction.operations = []
627+
pendingTransaction.deletedKeys.clear()
622628

623629
// Mark the transaction as a truncate operation. During commit, this triggers:
624630
// - Delete events for all previously synced keys (excluding optimistic-deleted keys)

0 commit comments

Comments
 (0)