参考Be wary of garbage collection 先看段代码:
echo "Stage 1: Mem usage is: ", memory_get_usage(), "\n"; $arr = array(); for ($i = 0; $i < 1000000; ++$i) { $arr[] = rand(); } echo "Stage 2: Mem usage is: ", memory_get_usage(), "\n"; $foo = 1; $bar = 2; echo "Stage 3: Mem usage is: ", memory_get_usage(), "\n"; $foo = $arr; $bar = $arr; echo "Stage 4: Mem usage is: ", memory_get_usage(), "\n"; $arr = array(); echo "Stage 5: Mem usage is: ", memory_get_usage(), "\n"; $bar[] = "hello, world"; echo "Stage 6: Mem usage is: ", memory_get_usage(), "\n"; $foo = array(); echo "Stage 7: Mem usage is: ", memory_get_usage(), "\n"; 运行结果:
Stage 1: Mem usage is: 37712 Stage 2: Mem usage is: 60232136 Stage 3: Mem usage is: 60232248 Stage 4: Mem usage is: 60232248 Stage 5: Mem usage is: 60232288 Stage 6: Mem usage is: 104426704 Stage 7: Mem usage is: 60242672 看stage 4,
...