perf: reduce per-row and per-access overhead in entity and model casting
メンテナーはふだん 1 日以内に返信
まだ誰も着手していません。
評価
- 難易度
- 4/5
- 見積もり時間
- 3〜5日
- 初心者へのやさしさ
- 35/100
- issue の種類
- リファクタリング
- 明瞭さ
- おおむね明確
- 活発さ
- 活発
- 技術スタック
- php
- 領域
- backend, performance
調査の方向性
Start with DataCaster::castAs() for the cast-type parsing, DataConverter::reconstruct() for the duplicate syncOriginal() call after injectRawData(), and Entity::__get(), __set() and toArray() for the getter/setter lookup. Run the benchmark or the DataCaster, DataConverter and Entity tests before and after each of the three commits. Done means the listed tests pass, including the documented behavior change for entities that override injectRawData(), and the proposal's timing targets hold.
索引モデルが issue の本文から書いたものです。
説明
Problem
Loading rows through a model with casts, especially as entities, repeats the same work on every row and every field:
DataCaster::castAs()parses the type string on every cast. For each value it runsstr_starts_with, amatch, apreg_match(),explode/array_map(trim)and atrim, all to turn something like'?int'or'json-array'into a handler key and params. The handler itself often costs less than the parsing.DataConverter::reconstruct()callssyncOriginal()twice for each entity. It callsinjectRawData(), which already callssyncOriginal(), and then callssyncOriginal()again. When attributes hold arrays or objects, each sync normalizes them and runsjson_encode().Entity::__get()and__set()rebuild the getter or setter name on every access. They runstr_replace/ucwords, then make twomethod_exists()calls.toArray()repeats this for every key.
Measurements
PHP 8.3 on macOS, OPcache on, production mode, warm. The test entity has 10 columns, 6 casts (int, ?int, bool, json-array, float, int-bool) and the default $dates.
| Case | Time |
|---|---|
1000 rows → arrays (fromDataSource) |
3.2 ms |
1000 rows → entities (reconstruct) |
6.3 ms |
| 1000 rows → entity with no casts | 2.0 ms |
| Step | Cost |
|---|---|
castAs() for an int field |
0.33 µs |
IntegerCast::get() called directly |
0.07 µs |
syncOriginal() with an array attribute |
1.2 µs per call |
Getter-name build + 2× method_exists() |
~0.1–0.2 µs per access |
__get() on a plain field |
0.46–0.58 µs |
toArray() with 10 keys |
7.6–11 µs |
Proposal
1. Cache parsed cast types (DataCaster)
Add a private static cache keyed by the type string. It stores only the parsed result: base type, params and the nullable flag.
- Handlers are not cached. Each instance still looks up the handler in its own
$castHandlers, so instances with different custom handlers keep working. - The non-strict
'nullable'param is still added after the cache lookup. - An unknown type still throws on every call.
- Why static: each entity has its own
DataCaster, so a per-instance cache would rarely get a hit. The parse depends only on the string, so the cache is safe across Worker Mode requests. It also can't grow without limit, because type strings come from code, not from input.
2. Sync originals once (DataConverter::reconstruct())
Remove the second syncOriginal() call. injectRawData() already syncs.
3. Per-class getter/setter map (Entity)
On the first access, build a map of each entity class's get*, _get*, set* and _set* methods using ReflectionClass::getMethods(), with lowercase keys. Lookups then replace the two method_exists() calls.
- Bounded memory: the map depends on the class, not on input. Keys passed to
fill()from request data can't make it grow. - Same lookup rules: lowercase keys match PHP's case-insensitive method names. Reflection includes private methods, so results match
method_exists()exactly.
Estimated gains
Fixes 1 and 2 bring 1000 entities from about 6.3 ms to about 3.6 ms, roughly 40% faster. Array results drop from about 3.2 ms to about 1.7 ms. Fix 3 removes about 25–35% of the cost of each __get()/__set() call, which matters most in toArray() and in views that read many properties.
These are estimates from micro-benchmarks, not from the final code.
Behavior changes (4.8)
Only fix 2 changes behavior. If an app entity overrides injectRawData() without calling syncOriginal(), reconstruct() no longer syncs for it. Such an entity will report every field as changed after a find(), and save() will write all columns. That override is already broken for any other caller of injectRawData(). This will be listed in the v4.8.0 changelog under "Behavior Changes", with a note in upgrade_480.rst saying overrides must call syncOriginal().
Fixes 1 and 3 change no behavior.
Not changing
- Lazy
DataCastercreation in theEntityconstructor (~5%). Subclasses can read the protected$dataCasterproperty directly and would getnull. - The non-strict
is_subclass_of()checks and thetoArray()filter closure. Each costs under 2%.
Plan
One PR with three commits, one per fix. Fix 2 also includes the changelog and upgrade-guide entries.
Tests
DataCasterTest:- Two instances with the same type string but different custom handlers each call their own handler.
- Non-strict
?typestill addsnullable, and strict mode doesn't. - An unknown type throws on every call.
DataConverterTest:- A reconstructed entity reports
hasChanged() === false. - An entity that overrides
injectRawData()without syncing now reports changes. This test documents the behavior change.
- A reconstructed entity reports
EntityTest:- Getter lookup ignores case.
_getXwins overgetX.- Inherited getters are found.
- A private getter behaves as it does today.
- Maps are kept separate for each class.
Related
- #10615, #10616, #10617
- 主要言語
- PHP
- スター
- 6k
- フォーク
- 2k
- 平均マージ
- 1日 22時間
- マージ済み PR(30日)
- 59
環境構築
- Dockerfile・Docker Compose ファイルなし
- プルリクエストのテンプレートあり
- コントリビューションガイドを読む
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
codeigniter4/CodeIgniter4 のほかの issue
-
難易度 2/5 1〜3時間 初心者へのやさしさ 72/100
codeigniter4/CodeIgniter4#10616 · コメント 1 件 ·
メンテナーはふだん 1 日以内に返信
-
難易度 3/5 1〜2日 初心者へのやさしさ 62/100
codeigniter4/CodeIgniter4#10617 · コメント 1 件 ·
メンテナーはふだん 1 日以内に返信
-
難易度 4/5 3〜5日 初心者へのやさしさ 25/100
codeigniter4/CodeIgniter4#10615 · コメント 1 件 ·
メンテナーはふだん 1 日以内に返信
-
bug
難易度 4/5 3〜5日 初心者へのやさしさ 48/100
codeigniter4/CodeIgniter4#10589 · コメント 3 件 ·
メンテナーはふだん 1 日以内に返信
-
dev
難易度 5/5 1週間以上 初心者へのやさしさ 25/100
codeigniter4/CodeIgniter4#10427 · コメント 5 件 ·
メンテナーはふだん 1 日以内に返信
codeigniter4/CodeIgniter4 の issue をすべて見る
似ている issue
-
難易度 2/5 1〜3時間 初心者へのやさしさ 84/100
scanaislop/aislop#476 ·
メンテナーはふだん 1 日以内に返信
-
難易度 2/5 1〜3時間 初心者へのやさしさ 78/100
components-web-app/api-components-bundle#403 ·
メンテナーはふだん 1 日以内に返信
-
難易度 2/5 1〜3時間 初心者へのやさしさ 74/100
mollie/PrestaShop#1566 ·
メンテナーはふだん 1 日以内に返信
-
難易度 2/5 1〜3時間 初心者へのやさしさ 72/100
components-web-app/docs#193 ·
-
docs: add Python and PHP examples to docs/api.md対応中かも @gaurika-analyst が今日担当しました。 オープンdocumentation good first issue
難易度 2/5 1〜3時間 初心者へのやさしさ 85/100
djazairdev/wilayas#12 · コメント 1 件 ·
メンテナーはふだん 1 日以内に返信