Premature Optimisation
debt(d7/e5/b5/t7)
Closest to 'only careful code review or runtime testing' (d7). detection_hints.automated is 'no' — profilers like blackfire/xdebug can reveal that optimisations aren't on hot paths, but identifying premature optimisation requires human judgement in code review.
Closest to 'touches multiple files / significant refactor in one component' (e5). The quick_fix says write readable code first then profile, but unwinding existing premature optimisations (caches, contorted algorithms, avoided abstractions) typically means refactoring multiple sites where the over-optimisation has spread.
Closest to 'persistent productivity tax' (b5). applies_to spans web/cli/queue contexts; premature optimisations sprinkled through code (avoided OOP, complex caching, micro-optimised loops) slow down every future maintainer who has to decode why the code is shaped oddly.
Closest to 'serious trap' (t7). The misconception is exactly that 'premature optimisation' means never think about performance — leading developers to either over-optimise everything or swing the other way and ignore algorithmic complexity entirely. The phrase contradicts its actual meaning for most who haven't read Knuth.
Also Known As
TL;DR
Explanation
Donald Knuth's famous observation — 'premature optimisation is the root of all evil' — warns against sacrificing code clarity for performance improvements that are speculative or negligible. Most performance problems lie in a small fraction of the code; optimising the wrong parts wastes time and produces harder-to-maintain code. The correct approach: write clear, correct code first; measure with a profiler to find real bottlenecks; optimise only what the data confirms is slow. In PHP, micro-optimisations (avoiding function calls, hand-rolling loops) almost never matter — I/O and query patterns almost always do.
Common Misconception
Why It Matters
Common Mistakes
- Micro-optimising loop constructs (for vs foreach vs while) without benchmarking actual impact.
- Using static methods or avoiding OOP for 'performance' in application code where the overhead is negligible.
- Caching results before measuring whether the operation is actually slow.
- Choosing a complex algorithm over a simple one for scale that the application will never reach.
Code Examples
// Micro-optimised before profiling — complex and wrong
public function getActiveUsers(): array {
// Avoid array_filter — 'too slow'
$result = [];
$users = $this->users;
$count = count($users); // cache count 'for speed'
for ($i = 0; $i < $count; $i++) {
if ($users[$i]->active) $result[] = $users[$i];
}
return $result;
}
// Write the clear version first — profile before optimising
public function getActiveUsers(): array {
return array_values(array_filter($this->users, fn($u) => $u->active));
}
// If this is actually slow (profiler shows it) — fix the query, not the PHP:
// SELECT * FROM users WHERE active = 1 (let the DB filter, not PHP)