codecamp

PHP 资源自有的引用计数

资源自有的引用计数

zval通过引用计数来节省内存的,这个我们都知道了,但你可能不知道的是,某个zval对应的{资源}在实现时也使用了引用计数这种概念,也就是有了两种引用计数!

{资源}对应的zval的类型是IS_RESOURCE,它并不保存最终的数据,而只保存一个数字,即EG(regular_list)中的数字索引。

当{资源}被创建时,比如我们调用sample_fopen()函数:

$a = sample_fopen('notes.txt', 'r');
//此时:var->refcount__gc = 1, rsrc->refcount = 1

$b = $a;
//此时:var->refcount__gc = 2, rsrc->refcount = 1

unset($b);
//此时:var->refcount__gc = 1, rsrc->refcount = 1

/*
 下面来个复杂的!
 */

$b = $a;
$c = &$a;
//此时:
/* 
    bvar->refcount = 1, bvar->is_ref = 0
    acvar->refcount = 2, acvar->is_ref = 1
    rsrc->refcount = 2 
*/

现在,如果我们unset($b),内核只会把rsrc->refcount的值减1。只有当rsrc->refcount的值为0时,我们预设的dtor释放函数才会被激活并调用。

PHP Persistent Resources
PHP 小结
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

PHP ini配置文件

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }