通过引用保存值时的内存使用情况

$myStr = '';
for ($i = 0; $i<999500; $i++) {
    $myStr .= chr(rand(0,127));
}
echo round(memory_get_usage()/1024/1024,2) . ' Mb';

I got 1.27 Mb

$myStr = '';
for ($i = 0; $i<999500; $i++) {
    $myStr .= chr(rand(0,127));
}
$myStr2 = &$myStr;
echo round(memory_get_usage()/1024/1024,2) . ' Mb';

I save myStr to myStr2 By reference, and I got 1.27 Mb

$myStr = '';
for ($i = 0; $i<999500; $i++) {
    $myStr .= chr(rand(0,127));
}
$myStr2 = $myStr;
echo round(memory_get_usage()/1024/1024,2) . ' Mb';

$myStr2 = $myStr also I got 1.27 Mb. What's going on? Why I got 1.27 Mb, instead 2.54 Mb?

By assigning a variable to another variable in PHP, PHP will not duplicate the variable's data immediatly for memory optimization reasons.

Only at the time you actually change one of the two variables, PHP will duplicate the data and then only change one of the two variables data:

$myStr2 = $myStr; # this won't copy the data.
$myStr2 .= 'X'; # this will trigger copy on write.

This optimzation is called "copy on write" (Wikipedia).

If you want to get a full scientific read on the topic, please see:

PHP does copy on write : as long as you only read from your second variable (and not write to it), it's not really copied from the first one.