Changeset View
Changeset View
Standalone View
Standalone View
src/docs/contributor/n_plus_one.diviner
Show All 33 Lines | cats: | ||||
... | ... | ||||
The problem with this is that each query has quite a bit of overhead. **It is | The problem with this is that each query has quite a bit of overhead. **It is | ||||
//much faster// to issue 1 query which returns 100 results than to issue 100 | //much faster// to issue 1 query which returns 100 results than to issue 100 | ||||
queries which each return 1 result.** This is particularly true if your database | queries which each return 1 result.** This is particularly true if your database | ||||
is on a different machine which is, say, 1-2ms away on the network. In this | is on a different machine which is, say, 1-2ms away on the network. In this | ||||
case, issuing 100 queries serially has a minimum cost of 100-200ms, even if they | case, issuing 100 queries serially has a minimum cost of 100-200ms, even if they | ||||
can be satisfied instantly by MySQL. This is far higher than the entire | can be satisfied instantly by MySQL. This is far higher than the entire | ||||
server-side generation cost for most Phabricator pages should be. | server-side generation cost for most Phorge pages should be. | ||||
= Batching Queries = | = Batching Queries = | ||||
Fix the N+1 query problem by batching queries. Load all your data before | Fix the N+1 query problem by batching queries. Load all your data before | ||||
iterating through it (this is oversimplified and omits error checking): | iterating through it (this is oversimplified and omits error checking): | ||||
$cats = load_cats(); | $cats = load_cats(); | ||||
$hats = load_all_hats_for_these_cats($cats); | $hats = load_all_hats_for_these_cats($cats); | ||||
Show All 27 Lines |
Content licensed under Creative Commons Attribution-ShareAlike 4.0 (CC-BY-SA) unless otherwise noted; code licensed under Apache 2.0 or other open source licenses. · CC BY-SA 4.0 · Apache 2.0