PHP:在循环内或外实例化类在占用内存上有很大的区别

先来一个test1.php

1
2
3
4
5
6
7
8
9
10
11
12
13
class ABC{
public $numBox = array();
public function ddd(){
for($i = 1; $i <= 600; $i++){
$this->numBox[] = mt_rand(1,1000000);
}
echo 'Now memory_get_usage: '.memory_get_usage().'<br />';
}
}
$instance = new ABC();
for($i = 0; $i< 50; $i++){
$instance->ddd();
}

这是test1.php的运行结果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
Now memory_get_usage: 422728
Now memory_get_usage: 474824
Now memory_get_usage: 522824
Now memory_get_usage: 579024
Now memory_get_usage: 627024
Now memory_get_usage: 675024
Now memory_get_usage: 739408
Now memory_get_usage: 787416
Now memory_get_usage: 835416
Now memory_get_usage: 883416
Now memory_get_usage: 931416
Now memory_get_usage: 979416
Now memory_get_usage: 1027416
..................

再来一个test2.php

1
2
3
4
5
6
7
8
9
10
11
12
13
class ABC{
public $numBox = array();
public function ddd(){
for($i=1; $i<=600; $i++){
$this->numBox[] = mt_rand(1,1000000);
}
echo 'Now memory_get_usage: '.memory_get_usage().'<br />';
}
}
for($i = 0; $i < 50; $i++){
$instance = new ABC();
$instance->ddd();
}

这是test2.php的运行结果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Now memory_get_usage: 422728
Now memory_get_usage: 422712
Now memory_get_usage: 422712
Now memory_get_usage: 422712
Now memory_get_usage: 422712
Now memory_get_usage: 422712
Now memory_get_usage: 422712
Now memory_get_usage: 422712
Now memory_get_usage: 422712
Now memory_get_usage: 422712
Now memory_get_usage: 422712
Now memory_get_usage: 422712
Now memory_get_usage: 422712
Now memory_get_usage: 422712
Now memory_get_usage: 422712
Now memory_get_usage: 422712
Now memory_get_usage: 422712
............................