I'm developing a PHP script that loops/iterates more that 10,000 times:
foreach ($array_with_items as $item) {
// Instantiate the object
$obj_car = new CarAds($puk, 'ENG', '5');
$obj_car->detail1 = "Info about detail1";
$obj_car->detail2 = "Info about detail2";
$obj_car->detail3 = "Info about detail3";
$obj_car->detail4 = "Info about detail4";
// Saves to the database
$obk_car->save;
}
When I run this code my machine runs out of memory. What can I do to clean the memory in this foreach cycle?
This foreach loop is faster because the local variable that stores the value of the element in the array is faster to access than an element in the array. The forloop is faster than the foreach loop if the array must only be accessed once per iteration.
Foreach performance is approximately 6 times slower than FOR / FOREACH performance. The FOR loop without length caching works 3 times slower on lists, comparing to arrays. The FOR loop with length caching works 2 times slower on lists, comparing to arrays.
forEach() can be implemented to be faster than for-each loop, because the iterable knows the best way to iterate its elements, as opposed to the standard iterator way. So the difference is loop internally or loop externally.
There is no major "performance" difference, because the differences are located inside the logic. You use foreach for array iteration, without integers as keys. You use for for array iteration with integers as keys. etc.
You are instantiating as CarAds objects as your $array_with_items item count. Each one allocate memory.
After the save() method you should deallocate the object with the unset() function:
// Saves to the database
$obj_car->save;
// Unset unneeded object
unset($obj_car);
You can check your memory consumption with the memory_get_usage() (see http://php.net/manual/en/function.memory-get-usage.php)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With