php内存与垃圾回收

内存和垃圾回收

每一个php变量都存储在一个zval的容器中,包含变量名和值以及is_ref->是否属于引用合集 refcount->指向容器的变量个数
定义以下变量:
$a="hello";
xdebug_debug_zval('a');

输出结果:
a:
(refcount=0, is_ref=0)string 'hello' (length=5)

此时我们继续定义:

var_dump(memory_get_usage());
$a="hello";
var_dump(memory_get_usage());
$b=$a;
var_dump(memory_get_usage());
$c=&$a;
var_dump(memory_get_usage());
xdebug_debug_zval('a');
xdebug_debug_zval('b');
xdebug_debug_zval('c');
unset($a);
var_dump(memory_get_usage());
unset($b);
var_dump(memory_get_usage());
unset($c);
var_dump(memory_get_usage());

输出以下结果:

D:\phpStudy\WWW\me.php:2:int 368384
D:\phpStudy\WWW\me.php:4:int 368384
D:\phpStudy\WWW\me.php:6:int 368384
D:\phpStudy\WWW\me.php:8:int 368408
a:
(refcount=2, is_ref=1)string 'hello' (length=5)
b:
(refcount=0, is_ref=0)string 'hello' (length=5)
c:
(refcount=2, is_ref=1)string 'hello' (length=5)

D:\phpStudy\WWW\me.php:17:int 368408

D:\phpStudy\WWW\me.php:22:int 368408

D:\phpStudy\WWW\me.php:26:int 368384

unset()方法则是让refcount设置为0
如果发现一个zval容器中的refcount在增加,说明不是垃圾
如果发现一个zval容器中的refcount在减少,如果减到了0,直接当做垃圾回收
如果发现一个zval容器中的refcount在减少,并没有减到0,PHP会把该值放到缓冲区,当做有可能是垃圾的怀疑对象
当缓冲区达到临界值,PHP会自动调用一个方法取遍历每一个值,如果发现是垃圾就清理

你可能感兴趣的:(php)