RE: [PHP] Return Values Copied? Copied if By Reference?

From: Date: Thu, 27 Jul 2006 18:27:22 +0000
Subject: RE: [PHP] Return Values Copied? Copied if By Reference?
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-239844@lists.php.net to get a copy of this message
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

« previous php.general (#239844) next »