學習PHP記憶體回收機制瞭解引用計數器的概念

來源:互聯網
上載者:User
php變數存在一個叫"zval"的變數容器中,"zval"變數容器包括含變數的類型和值,還包括額外的兩個位元組資訊,分別是“is_ref”表示變數是否屬於引用,“refcount”指向這個zval變數容器的變數個數。

如果你安裝了xdebug,就可以用xdebug_debug_zval()顯示“zval”的資訊了。如下:

  

  

結果:

str:

(refcount=1, is_ref=0),

string 'phpddt.com' (length=10)

只有當變數容器在”refcount“變成0時就被銷毀.當你unset()一個變數時,想要的“zval”中refcount就會減1,再來說說前幾天遇到的unset引用問題:

  

  

結果:

b:

(refcount=1, is_ref=0),string 'aaa' (length=3)

繼續說引用計數器問題,對於array和object符合類型情況又不一樣了:

 'aaa', 'b' => "bbb" );xdebug_debug_zval( 'arr' );$arr['aaa'] = $arr['a'];xdebug_debug_zval( 'arr' );?>

  

結果:

arr:

(refcount=1, is_ref=0),

array

'a' => (refcount=1, is_ref=0),string 'aaa' (length=3)

'b' => (refcount=1, is_ref=0),string 'bbb' (length=3)

arr:

(refcount=1, is_ref=0),

array

'a' => (refcount=2, is_ref=0),string 'aaa' (length=3)

'b' => (refcount=1, is_ref=0),string 'bbb' (length=3)

'aaa' => (refcount=2, is_ref=0),string 'aaa' (length=3)

可以看到看到原有的數組元素和新添加的數組元素關聯到同一個"refcount"2的zval變數容器.這裡我也只是起到拋磚引玉的作用。

具體關於PHP引用計數器可以參照手冊:http://php.net/manual/zh/features.gc.refcounting-basics.php

歡迎轉載! 原文地址: http://www.phpddt.com/php/gc-refcounting-basics.html ,轉載請註明地址,謝謝!

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.