background image

PHP 中使用 unset 销毁变量并内存释放问题

PHP 的 unset()函数用来清除、销毁变量,不用的变量,我们可以用 unset()将它销毁。但是某
些时候,用

unset()却无法达到销毁变量占用的内存!

一览

php 代码如下:

 

for

 ( 

$i

 = 1; 

$i

 < 100; 

$i

++ ) { 

$str

 = 

str_repeat

('01234567', 

$i

); 

$a

 = memory_get_usage(); 

unset(

$str

); 

$b

 = memory_get_usage(); 

echo

 "\n 

".

$i

.': '.(

$b

 - 

$a

).' Bytes.'; 


 
从结果看出:

 

8 x 32 = 256 在 256 字节长的时候才真正有必要释放内存,有些人说,不如直接

$str

 = null

来的速度快。
结果如下:

 

1: 0 Bytes. 
2: 0 Bytes. 
3: 0 Bytes. 
4: 0 Bytes. 
5: 0 Bytes. 
6: 0 Bytes. 
7: 0 Bytes. 
8: 0 Bytes. 
9: 0 Bytes. 
10: 0 Bytes. 
11: 0 Bytes. 
12: 0 Bytes. 
13: 0 Bytes. 
14: 0 Bytes. 
15: 0 Bytes. 
16: 0 Bytes. 
17: 0 Bytes. 
18: 0 Bytes. 
19: 0 Bytes. 
20: 0 Bytes. 
21: 0 Bytes. 
22: 0 Bytes.