Skip to content
Open
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
15 changes: 13 additions & 2 deletions packages/payload/src/collections/dataloader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,17 @@ const batchAndLoadDocs =
}
}

// Map each cache key to its index up front so the per-doc lookup below is O(1)
// instead of a full `keys.findIndex` scan. `keys` is fixed for this batch, so a
// single pass here turns the doc-placement loop from O(n²) into O(n) over the
// batch size. First occurrence wins, mirroring `findIndex`.
const keyToIndex = new Map<string, number>()
for (let i = 0; i < keys.length; i++) {
if (!keyToIndex.has(keys[i]!)) {
keyToIndex.set(keys[i]!, i)
}
}

// Run find requests one after another, so as to not hang transactions

for (const [batchKey, ids] of Object.entries(batchByFindArgs)) {
Expand Down Expand Up @@ -149,9 +160,9 @@ const batchAndLoadDocs =
showHiddenFields,
transactionID: req.transactionID!,
})
const docsIndex = keys.findIndex((key) => key === docKey)
const docsIndex = keyToIndex.get(docKey)

if (docsIndex > -1) {
if (docsIndex !== undefined) {
docs[docsIndex] = doc
}
}
Expand Down
Loading