Re: Return Values Copied? Copied if By Reference?

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



KermodeBear wrote:
Robert Cummings wrote:

Then how come when I do a foreach on an array (without modifying anything within the foreach), it still makes a copy of the array that consumes memory? I think it's dangerous to generalize that it's always best to let PHP make copies of things. In the foreach situation, the preferred solution when memory is a problem is to either use a reference, or have foreach iterate over the keys of the array.

Regards, Adam.

-----

PHP doesn't seem to make a real copy of data until one of the copies is
modified, making it necessary to create a new set of data. So, it is pretty
smart about that.

Here is a small CLI script that seems to support this:
<?php
$a_array = array();
for($i = 0; $i < 10000; $i++) {
        $a_array[] = time(); // Just an arbitrary piece of data
}
echo 'Memory Usage: ' . memory_get_usage() . "\n";
echo "Making a copy of the array.\n";
$a_copy = $a_array;
echo 'Memory Usage: ' . memory_get_usage() . "\n";
echo "Modifying the copy:\n";
$a_copy[] = time();
echo 'Memory Usage: ' . memory_get_usage() . "\n";
?>

On my machine, this displays:
Memory Usage: 640280
Making a copy of the array.
Memory Usage: 640440
Modifying the copy:
Memory Usage: 1106056

-K. Bear

I note that your example doesn't use a foreach loop, which is what my post was about.

Some testing shows my original premise was wrong, but it's still possible to get PHP to copy the array when it doesn't need to. In this case, using a reference can save memory even when a reference isn't needed. If you want to modify the original array in the foreach, then it is better to step over the array yourself and save memory, or pass the foreach a reference to the array to stop it from doing a copy.

I'm just trying to say, I don't think it's always a good idea to rely on the language deciding when to copy. Sometimes it's a good idea to use a reference to stop the copy if memory is a concern.

Regards, Adam Zey.

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux