PHP memory management and garbage collection

PHP5 memory management

object passed

PHP5 Zend Engine II used, the object is stored in a separate structure Object Store in variables that unlike other ships stored in the zval (as in PHP4 objects and stored in a general variable Zval). In Zval pointer instead of storing only content objects (value). When we copy an object or when an object as a parameter passed to a function, we do not need to copy the data. Only by maintaining the same object pointer zval another particular object of this notification is now directed Object Store. Since the object itself is located Object Store, we have made any changes to it will affect all holders of the object pointers structure ---- zval performance in the program is that any change will affect the target object to the source object. It looks like the PHP object is always passed by reference (reference), and therefore PHP objects by default as "reference", as you no longer need to use PHP4 as in & declared.

Garbage collection

in some languages, the most typical such as C, you need to explicitly allocate memory required when you create a data structure. Once you allocate memory, it can store information in a variable. You also need to free the memory at the end of the use of variables, which makes the machine frees memory for other variables, without wearing out the memory.

PHP can be automated memory management, clear the object is no longer needed. PHP uses reference counting (reference counting) this simple garbage collection (garbage collection) mechanism. Each object contains a reference counter connected to each reference object counter is incremented. When reference is set to leave the living space or NULL, the counter is decremented. When an object's reference count is zero, PHP know that you will no longer need to use this object to release its memory space occupied.

E.g:

code show as below:

<?php  

class Person{  

}  

function sendEmailTo(){  

}  

$haohappy = new Person( );    

// 建立一个新对象:  引用计数    Reference count = 1  

$haohappy2 = $haohappy;        

// 通过引用复制:  Reference count = 2  

unset($haohappy);            

// 删除一个引用: Reference count = 1  

sendEmailTo($haohappy2);       

// 通过引用传递对象:    

// 在函数执行期间:  

//  Reference count = 2  

// 执行结束后:  

// Reference count = 1  

unset($haohappy2);            

// 删除引用: Reference count = 0 自动释放内存空间  

?>

Guess you like

Origin www.cnblogs.com/yudapeng/p/11562842.html