PHP में for और foreach loops के performance characteristics और कब कौन सा उपयोग करें।
मूल अंतर
for- Index-based, manual control, slightly faster for numeric arraysforeach- Iterator-based, cleaner syntax, copies array by default (PHP 7 तक)
Performance Test Code
<?php
$arr = range(1, 100000); // 100k elements
// Test 1: foreach by value (copies array in PHP < 7)
$start = microtime(true);
foreach ($arr as $v) { $v += 1; }
echo "foreach (value): " . (microtime(true) - $start) . "s\n";
// Test 2: foreach by reference (modifies original, no copy)
$start = microtime(true);
foreach ($arr as &$v) { $v += 1; }
echo "foreach (ref): " . (microtime(true) - $start) . "s\n";
// Test 3: for loop
$start = microtime(true);
for ($i = 0, $len = count($arr); $i < $len; $i++) {
$arr[$i] += 1;
}
echo "for loop: " . (microtime(true) - $start) . "s\n";
// Test 4: foreach read-only (no modification)
$start = microtime(true);
foreach ($arr as $v) { /* read only */ }
echo "foreach (read): " . (microtime(true) - $start) . "s\n";
Typical Results (PHP 8.x, 100k elements)
| Loop Type | Time | Notes |
|---|---|---|
for (cached count) | ~2.5ms | सबसे तेज़ numeric arrays के लिए |
foreach (by reference) | ~3.0ms | Modification के लिए अच्छा |
foreach (by value, read) | ~2.8ms | PHP 7+ में copy-on-write, fast |
foreach (by value, modify) | ~5.0ms | PHP < 7 में full copy, slow |
PHP Version Differences
- PHP 5.x:
foreachहमेशा array copy करता है → slow for large arrays - PHP 7+: Copy-on-write optimization → read-only foreach fast
- PHP 8+: Further optimizations, JIT compilation benefits
कब क्या उपयोग करें
| Scenario | Recommended | कारण |
|---|---|---|
| Simple iteration (read-only) | foreach | Clean, readable, fast enough |
| Array modification needed | foreach (... as &$v) | Direct modification, no copy |
| Numeric index manipulation | for | Index control, reverse, step |
| Associative array iteration | foreach | Keys access आसान |
| Performance critical (millions) | for या foreach &$v | Micro-optimization |
| Multi-dimensional arrays | foreach | Nested foreach natural |
महत्वपूर्ण: Reference Cleanup
<?php
$arr = [1, 2, 3];
foreach ($arr as &$v) {
$v *= 2;
}
unset($v); // महत्वपूर्ण! $v अभी भी last element को reference करता है
// बिना unset के:
$v = 999; // $arr[2] भी 999 हो जाता है!
print_r($arr); // [2, 4, 999] - Bug!
Modern PHP (8.1+) Alternatives
// array_map - functional, immutable
$doubled = array_map(fn($x) => $x * 2, $arr);
// array_walk - in-place modification
array_walk($arr, fn(&$v) => $v *= 2);
// Generator for memory efficiency
function processLargeArray(iterable $data) {
foreach ($data as $item) {
yield $item * 2;
}
}
निष्कर्ष
अधिकांश मामलों में पठनीयता के लिए
foreachउपयोग करें। Performance critical code में हीforया reference-basedforeachपर विचार करें। Premature optimization से बचें।