我试图检查memory_get_peak_usage()方法,我尝试在for循环中动态创建对象,并尝试打印我的php脚本使用的内存。这是代码: -
$objArr = array();
for( $i=1; $i<=100; $i++ ){
echo "creating employee == " . memory_get_peak_usage()/1024 . " Kbs\n";
$objArr[$i] = new CEmployee();
}
exit;
这是让我困惑的结果: -
creating employee == 4156.84375 Kbs
creating employee == 6619.640625 Kbs
creating employee == 6619.640625 Kbs
creating employee == 6619.640625 Kbs
...
...(up to 40 lines from 2nd line same result as above and then from 41 line changed)
creating employee == 6623.5546875 Kbs
creating employee == 6631.234375 Kbs
creating employee == 6638.9140625 Kbs
creating employee == 6646.59375 Kbs
creating employee == 6654.2734375 Kbs
creating employee == 6661.953125 Kbs
creating employee == 6669.6328125 Kbs
creating employee == 6677.3125 Kbs
creating employee == 6684.9921875 Kbs
....
....
我没有得到php如何为对象分配内存。我在Windows 7上的命令行界面上运行脚本
更新代码: -
gc_collect_cycles();
for( $i=1; $i<=100; $i++ ){
echo "creating employee == " . memory_get_usage()/1024 . " Kbs\n";
$objArr[$i] = new CEmployee();
$objArr[$i]->setEmployeeNumber($i);
}exit;
答案 0 :(得分:2)
正如您所看到的,它确实会增加内存使用量:
但是,您可能已准备好进行垃圾回收的数据,因此当您创建新的CEmployee
时,它可能正在使用该空间。
尝试在循环前运行gc_collect_cycles()
并使用memory_get_usage()
来获得更准确的阅读。