Skip to content

perf(core): avoid per-owner scans on the owning side of M:N - #8392

Merged
B4nan merged 1 commit into
mikro-orm:masterfrom
irontaek:perf/owning-m2n-hydration
Oct 5, 2026
Merged

B4nan merged 1 commit into
mikro-orm:masterfrom
irontaek:perf/owning-m2n-hydration

Conversation

@irontaek

@irontaek irontaek commented Oct 5, 2026

Copy link
Copy Markdown
Contributor

Follow-up to #8391, which handled the inverse side. This is the owning-side branch of initializeManyToMany, which I left out of that PR. Like #8391, it only runs on drivers without pivot tables (MongoDB).

For each owner, the old code ran children.filter(child => collection.contains(child)) over every loaded child. Without a custom order it then sorted the result with order.indexOf. The new code builds a Map from each loaded child to its position once. For each owner it reads the owner's own references and keeps the ones that were loaded. The order stays the same:

  • Default order: the owner's reference order. The references are already in that order, so no sort is needed.
  • Custom order: the order of the loaded children. This is now a sort by the indexed position instead of a filter over all children.

Where it matters

Below is em.find(Book, {}, { populate: ['tags'] }) against a local MongoDB 8.2, using the test entities. Book.tags has orderBy: { name: 'asc' }, so this exercises the custom-order path. Each book has 3 tags. Median of 15 runs; before and after were run alternately, twice each:

tags · books before after
50 · 500 44.0 / 20.9 ms 24.1 / 25.1 ms (noise)
200 · 2000 121.1 / 84.0 ms 92.4 / 80.3 ms (noise)
1000 · 10000 1232 / 968 ms 423 / 424 ms

Up to a few thousand books, the difference is within noise. The gain shows up when both the owner count and the loaded children grow.

I also benchmarked the loop on its own, with the output compared at every size. With the default order it is faster from 10 owners × 30 children (1.5×) up to 175× at 1000 × 5000. With a custom order, the smallest case (10 × 30) is about 1 µs slower because of the extra sort (0.7×). It breaks even around 20 × 100, and is 86× faster at 1000 × 5000.

Tests

I ran the Mongo test files against a local mongod. The failures match master: they are the suites that need MySQL, Postgres and other databases I don't have running locally.

To check the new code is really covered:

  • Making the branch hydrate nothing breaks 15 existing tests, including "many to many collection does have fixed order".
  • Dropping only the custom-order sort breaks "collection allows custom populate, where and orderBy".

With the change in place they all pass. oxfmt, oxlint and tsc --noEmit -p packages/core are clean.

https://claude.ai/code/session_01W9Mk18mBNfkPfgg3hYweKq

On drivers without pivot tables (MongoDB), hydrating the owning side of
a M:N relation filtered the full children list once per owner and then
sorted with indexOf. Index the loaded children once and read each
owner's references directly. The resulting order is unchanged: the
reference order by default, or the order of loaded children when a
custom order is used.
@codecov

codecov Bot commented Oct 5, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 99.66%. Comparing base (fa2eefa) to head (fc23c29).

Additional details and impacted files
@@           Coverage Diff            @@
##           master    #8392    +/-   ##
========================================
  Coverage   99.66%   99.66%            
========================================
  Files         293      293            
  Lines       32000    32000            
  Branches     8621     9185   +564     
========================================
  Hits        31894    31894            
  Misses        102      102            
  Partials        4        4            

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@B4nan B4nan left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

thanks

@B4nan
B4nan merged commit 39599a7 into mikro-orm:master Oct 5, 2026
26 checks passed
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.

2 participants