Skip to content

perf(core): group inverse M:N children in one pass - #8391

Merged
B4nan merged 2 commits into
mikro-orm:masterfrom
irontaek:perf/inverse-m2n-hydration
Oct 5, 2026
Merged

B4nan merged 2 commits into
mikro-orm:masterfrom
irontaek:perf/inverse-m2n-hydration

Conversation

@irontaek

@irontaek irontaek commented Oct 5, 2026

Copy link
Copy Markdown
Contributor

This only affects drivers without pivot tables (MongoDB). SQL drivers populate M:N through findChildrenFromPivotTable and never reach this branch.

On the inverse side of a M:N relation, initializeManyToMany ran children.filter(...) once per owner. That is O(owners × children). This change goes over the children once and groups them by owner, using the items of each child's owning collection. The order of children for each owner stays the same.

Where it matters

At small and medium sizes there is no visible difference. The gain shows up when both sides grow. Below is em.find(BookTag, {}, { populate: ['books'] }) against a local MongoDB 8.2, using the test entities (Book.tags owner, BookTag.books inverse), each book with 3 tags. Median of 9 runs; before and after were run alternately, twice each:

tags · books before after
10 · 50 9.9 / 14.1 ms 12.7 / 7.6 ms (noise)
20 · 200 17.7 / 31.2 ms 23.3 / 13.4 ms (noise)
50 · 500 33.7 / 44.5 ms 28.9 / 23.6 ms
200 · 2000 181.7 / 202.9 ms 146.4 / 95.3 ms
1000 · 10000 8798 / 6172 ms 733 / 464 ms

I also benchmarked the two loops in isolation, down to 10 owners × 30 children. The new version is not slower at any size, and the output was compared at every size.

Tests

  • I ran the Mongo test files against a local mongod. Results match master: the only failures are suites that need MySQL, Postgres and other databases I don't have running locally.
  • To check the branch is really covered, I replaced the grouping with a no-op. That breaks 13 existing Mongo tests (for example "many to many working with inverse side" and "nested populating"). With the change in place they all pass.
  • The SQLite suites pass too, but they don't reach this code path.
  • oxfmt is clean for the changed file.

The owning-side branch just below has the same per-owner filter plus an indexOf sort. I left it alone to keep this PR small.

https://claude.ai/code/session_01W9Mk18mBNfkPfgg3hYweKq

On drivers without pivot tables (MongoDB), populating the inverse side
of a M:N relation filtered the full children list once per owner, which
is O(owners x children). Build an owner -> children map in a single pass
over the children instead. Children order per owner is unchanged.
@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 (ef629d5) to head (c429b93).
⚠️ Report is 2 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff             @@
##           master    #8391      +/-   ##
==========================================
- Coverage   99.66%   99.66%   -0.01%     
==========================================
  Files         293      293              
  Lines       31995    31997       +2     
  Branches     8617     9182     +565     
==========================================
+ Hits        31889    31890       +1     
- Misses        102      103       +1     
  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 fa2eefa into mikro-orm:master Oct 5, 2026
26 checks passed
B4nan pushed a commit that referenced this pull request Oct 5, 2026
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

Co-authored-by: Minho Yoo <[email protected]>
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