RE: Return Values Copied? Copied if By Reference?

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

 



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

-- 
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