I wrote a file to test the memory usage of PHP. I found that the memory occupied by variables after release is different between arrays and objects. I would like to ask why. The following is the code, running in PHP 7.0 CLI mode.
Array:
<?php
function convert($size){
$unit=array('b','kb','mb','gb','tb','pb');
echo @round($size/pow(1024,($i=floor(log($size,1024)))),2).$unit[$i]."\n";
}
function a(){
$a = [];
for($i=0;$i<1000000;$i++){
$a[$i] = $i;
}
convert(memory_get_usage(true));
}
convert(memory_get_usage(true));
// 2M
a();
convert(memory_get_usage(true))
// 2M
Output:
2M
34M
2M
Object:
<?php
function convert($size){
$unit=array('b','kb','mb','gb','tb','pb');
echo @round($size/pow(1024,($i=floor(log($size,1024)))),2).$unit[$i]."\n";
}
function a(){
$a = new stdClass;
for($i=0;$i<1000000;$i++){
$a->$i = $i;
}
convert(memory_get_usage(true));
}
convert(memory_get_usage(true));
a();
convert(memory_get_usage(true))
Output:
2M
68M
32M
This question is very complicated. It’s about PHP’s garbage collection mechanism. I don’t understand it very thoroughly. I’ll share with you what I understand.
Each PHP process will be allocated a root buffer. During execution, every reference to the PHP data structure will be put into this buffer. Once the upper limit of the buffer is reached (usually 10,000), PHP will be triggered. Garbage collection mechanism to clean up some invalid resources.
If you change the number of loops to 5000 times, garbage collection will not be triggered. The memory value of the last two times should be the same. You can try it.
I read an article and hope it helps
Garbage collection