$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:
This optimzation is called “copy on write” (Wikipedia).
If you want to get a full scientific read on the topic, please see: