Interview question
What are common PHP coding practices that hurt performance, and how do you avoid them? कौन-सी common PHP coding practices performance को नुकसान पहुंचाती हैं?
Answer
| Anti-pattern | Better approach |
|---|---|
| Queries inside loops | Batch fetch before the loop / eager loading |
| Loading entire large files into memory | Stream with fopen()/fgets() or generators |
| Using count() inside a loop condition repeatedly | Store count in a variable before the loop |
| Overusing regular expressions for simple checks | Use native string functions (str_contains, str_starts_with) |
// Bad - recalculates count() every iteration
for ($i = 0; $i < count($items); $i++) { ... }
// Good
$total = count($items);
for ($i = 0; $i < $total; $i++) { ... }
// Bad - loads whole file
$data = file_get_contents('huge.csv');
// Good - streams line by line
$handle = fopen('huge.csv', 'r');
while (($line = fgets($handle)) !== false) {
// process line
}
fclose($handle);| Anti-pattern | बेहतर तरीका |
|---|---|
| Loop के अंदर queries | Loop से पहले batch fetch करें |
| बड़ी files पूरी memory में load करना | fopen()/fgets() से stream करें |
| Loop condition में count() बार-बार | Count को variable में store करें |
// खराब
for ($i = 0; $i < count($items); $i++) { ... }
// अच्छा
$total = count($items);
for ($i = 0; $i < $total; $i++) { ... }Was this answer clear?