When an ORM query slows down after the SQL returns
Imagine loading 3,000 authors with one book each. Once the database returns the rows, how much work should it take to put each book on its author? In a TypeORM reproduction using SQL.js and relationLoadStrategy: "query", going from 1,500 to 3,000 authors pushed the measured load time from 712 ms to 2,607 ms. Each author still had exactly one book. Benchmark and query
The first clue was an array-repeated-find finding from Loadwise. For each entity, TypeORM searched a list of groups for the group holding that same entity. If the groups are in order, the first lookup checks one group and the last checks all 3,000. That’s 4,501,500 comparisons to reconnect 3,000 entities to groups that already hold their original entity. Profiling also turned up an earlier stage where each parent scanned the relation-ID rows. A separate contributor, skpn, had already documented the same behavior and proposed an indexed implementation. Loadwise finding and profiling · Earlier independent report · Earlier proposed fix
The proposal in PR #13116 builds indexes for ordinary keys, walks the related entities in their loaded order, and assigns each group’s result directly to its original entity. At 3,000 authors, an earlier revision recorded 18.0 ms on the same SQL.js fixture. That number describes one dataset and one revision. If you benchmark your own loader, keep the number of children per parent fixed as you increase the parent count. Then try a parent with many children to expose extra copying or sorting inside each group. Proposed implementation, benchmark conditions, and tests
The hard part is deciding what counts as the same key. Two JavaScript objects containing identical bytes can be distinct Map keys. The database driver may consider them equal. An automated PR review raised an even subtler case: a binary ID subclass can override its hex formatter and produce a different string for the same bytes. A regression test for an index should compare its results with the old matcher on inputs like these. Check the child order and duplicate links as well as the number of matches. Binary-key review comment
As of November 30, 2026, PR #13116 was open and awaiting review. Current PR status
To check your own JavaScript or TypeScript project, run npx loadwise@0.7.0 check --only perf from its root. For regular use, install the npm package with npm install --save-dev loadwise. Share one useful finding or a false positive.
Disclosure: This article was generated with AI from the linked issues, benchmarks, and code review. The author of PR #13116 maintains Loadwise and disclosed AI assistance on the proposal.
原文:https://www.a8q9.cn/en/article/when-an-orm-query-slows-down-after-the-sql-returns-759b86.html