refactor(database): optimize _processForeignKeys() string allocations and loop invariants#10351
refactor(database): optimize _processForeignKeys() string allocations and loop invariants#10351gr8man wants to merge 2 commits into
Conversation
Refactors _processForeignKeys() to: - calculate invariant SQL fragments outside the loop - cache escaped table identifier - build SQL string locally before concatenating to the array, saving intermediate string allocations
michalsn
left a comment
There was a problem hiding this comment.
Thanks for the PR. The refactor appears behaviorally equivalent, but I'm not convinced the small performance gain justifies the added complexity without benchmark results.
The old code already used one sprintf(), and identifier escaping is reduced only for ALTER queries with multiple foreign keys. The common no-FK path also now performs unnecessary setup.
Could you add benchmarks, restore a fast return for no foreign keys, remove the unrelated formatting changes, and translate/remove the Polish comment?
- Restore fast return without foreign keys\n- Remove unrelated formatting changes\n- Remove non-English comment
433f70d to
d007add
Compare
|
php benchmark_fk.php [1] Time taken for 500000 calls WITHOUT foreign keys: 0.1973 seconds php benchmark_fk.php [1] Time taken for 500000 calls WITHOUT foreign keys: 0.2577 seconds `<?php require DIR . '/vendor/autoload.php'; use CodeIgniter\Database\Forge; class MockForge extends Forge $count = 500000; $db = new MockConnection([]); $forge->addField([ echo "--- BENCHMARK ---\n"; // SCENARIO 1: WITHOUT FOREIGN KEYS (Fast return path) echo "[1] Time taken for {$count} calls WITHOUT foreign keys: " . number_format($timeNoKeys, 4) . " seconds\n"; // SCENARIO 2: WITH FOREIGN KEYS // Then we call the method once, which processes all of them at once echo "[2] Time processing {$count} added foreign keys (1 call): " . number_format($timeWithKeys, 4) . " seconds\n"; |
michalsn
left a comment
There was a problem hiding this comment.
Thanks for addressing the feedback. This looks good to me, although the practical gain is quite small given the number of foreign keys we would normally process.
Description
Refactors
_processForeignKeys()inForge.phpto optimize performance and reduce memory allocations:fkSuffix,prefixSql) once outside the main loop.$this->db->escapeIdentifiers().sprintf()and string appending before performing a single concatenation to the$sqlsarray. This saves multiple intermediate array lookup and string allocations per foreign key.Checklist: