[nycphp-talk] PHP Scope in foreach construct.
Daniel Convissor
danielc at analysisandsolutions.com
Wed Jan 28 13:17:24 EST 2009
Hi Brent:
On Mon, Jan 26, 2009 at 12:50:38PM -0500, Brent Baisley wrote:
> foreach makes a copy of the array element you are processing. If the
> current "value" is large, like another array, then you have 2 large
> arrays.
That doesn't sound right. PHP is pretty smart about memory usage. When
a variable is utilized in a way that is only reading the value, a
reference is used. The variable is only copied when write operations are
happening. This is also the case, for example, for function parameters.
But if you need to modify the value and need to be frugal about memory
and are okay with modifying the initial variable, references do come in
handy.
But be warned, using references for values in foreach loops leads to very
strange behaviors once the loop exits.
Here's a test script verifying the memory usage issues:
SCRIPT
------
<?php
echo 'start: ' . memory_get_usage(true) . "\n";
$array = array(
str_repeat('1', 1000000),
str_repeat('1', 1000000),
str_repeat('1', 1000000),
);
echo 'set $array: ' . memory_get_usage(true) . "\n";
foreach ($array as $value) {
echo 'foreach $value: ' . memory_get_usage(true) . "\n";
$value = str_repeat('0', 1000000);
echo 'altered $value: ' . memory_get_usage(true) . "\n";
}
foreach ($array as &$value) {
echo 'foreach by ref $value: ' . memory_get_usage(true) . "\n";
$value = str_repeat('0', 1000000);
echo 'altered by ref $value: ' . memory_get_usage(true) . "\n";
}
echo 'end: ' . memory_get_usage(true) . "\n";
?>
OUTPUT
------
start: 262144
set $array: 3407872
foreach $value: 3407872
altered $value: 4456448
foreach $value: 3407872
altered $value: 4456448
foreach $value: 3407872
altered $value: 4456448
foreach by ref $value: 3407872
altered by ref $value: 3407872
foreach by ref $value: 3407872
altered by ref $value: 3407872
foreach by ref $value: 3407872
altered by ref $value: 3407872
end: 3407872
--Dan
--
T H E A N A L Y S I S A N D S O L U T I O N S C O M P A N Y
data intensive web and database programming
http://www.AnalysisAndSolutions.com/
4015 7th Ave #4, Brooklyn NY 11232 v: 718-854-0335 f: 718-854-0409
More information about the talk
mailing list