Skip to content

perf(documentArray): avoid O(n*m) id() lookup when setting a documentarray to a plain array - #16683

Merged
vkarpov15 merged 4 commits into
9.13from
vkarpov15/gh-16673
Nov 9, 2026
Merged

vkarpov15 merged 4 commits into
9.13from
vkarpov15/gh-16673

Conversation

@vkarpov15

Copy link
Copy Markdown
Collaborator

Fix #16673

Summary

#16673 points out that setting a document array to a plain array is extremely slow for large document arrays of 5000+ elements because of an id() lookup in a loop. That id() lookup is not strictly necessary; it was originally introduced in 5d5e1c823 (Oct 2011) as a mechanism to reuse subdocuments, presumably for performance. However, now that document array elements have an __parentArray pointer, a document array element should only be in one document array, so reusing an existing subdocument in a new document array is problematic.

To avoid extra overhead in the doc.arr = doc.toObject().arr case, which is surprisingly common, despite how much I advise against it, I added an extra check to see if the array being set is exactly equal, and, if so, reuse the existing array. That is consistent with the current behavior - currently doc.arr = doc.toObject().arr creates a new document array, but with nothing modified.

Examples

@vkarpov15 vkarpov15 added this to the 9.12.1 milestone Nov 7, 2026
@vkarpov15
vkarpov15 requested review from AbdelrahmanHafez and hasezoey and a balanced review from Copilot November 7, 2026 22:02

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@hasezoey hasezoey left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

LGTM

@vkarpov15 vkarpov15 modified the milestones: 9.12.1, 9.13 Nov 9, 2026
@vkarpov15
vkarpov15 marked this pull request as ready for review November 9, 2026 19:24
@vkarpov15
vkarpov15 changed the base branch from master to 9.13 November 9, 2026 19:31
@vkarpov15
vkarpov15 merged commit 42a0951 into 9.13 Nov 9, 2026
62 checks passed
@hasezoey
hasezoey deleted the vkarpov15/gh-16673 branch November 10, 2026 11:16
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Assigning a plain array to a document array is O(n*m): cast() calls prev.id() per element

3 participants