PHP7 PHP5 and comparative reference (Note)

php5 reference count after the introduction, refcount_gc used to record the number of times, while using is_ref_gc to whether the record is a reference type.

E.g

$a = 'hello';

//$a->zval1(type=IS_STRING,refcount_gc=1,is_ref_gc=0)

This time $ a pointer to a structure, mainly to see refcount_gc = 1, which is the reference count field, because the hello string is assigned to the $ a, so this time is a reference count hello

$b = $a;

$b,$a->zval1(type=IS_STRING,refcount_gc=2,is_ref_gc=0)

This time again assigned to the $ a $ b, and so this time $ a $ b simultaneously pointing to this structure, and reference count plus 1

$c = &$b;

//$a->zval1(type=IS_STRING,refcount_gc=1,is_ref_gc=0)

//$c,$b->zval2(type=IS_STRING,refcount_gc=2,is_ref_gc=1)

This time because the $ b assigned to the $ c, but a pass-way, so at this time we should separated, $ a is also pointing to the original structure, $ c and $ b point to the same time a new structure, this time is_ref_gc zval value will change, so that at this time zval must be separated, but in fact their value has not changed, which makes the need to maintain two values ​​in the heap of "hello" zval.

Let's take a look at the implementation of php7

php7 introduced a new type IS_REFERENCE to deal with this problem, first look at the structure of the body zend_reference:

struct _zend_reference{

zend_refcounted_h gc;

zval val;

};

$a = 'hello';

//$a->zend_string(refcount=1,val)

$b = $a;

//$b,$a->zend_string(refcount=2,val)

$c = &$b;

//$a->zend_string(refcount=2,val)

//$c,$b->zval(type=IS_REFERENCE,refcount=2)->zend_string(refcount=2,val)

From the above it can be seen, when using the & operator, will create a new intermediate structure zend_referenct, the experience points to the real structure zend_string structure, the reference count zend_string structure unchanged, while the structure of the reference count zend_reference to 2, because $ b $ c and now has a type will become zend_reference, so that the benefits of the original zend_string in memory is always only one (to avoid wasting memory by repeated application of the resulting string), easier maintain.

Guess you like

Origin www.cnblogs.com/sjks/p/10961099.html