当前位置:网站首页>Garbage collection mechanism of PHP (theoretical questions of PHP interview)

Garbage collection mechanism of PHP (theoretical questions of PHP interview)

2022-07-05 14:59:00 Back end regular developers


PHP Garbage collection mechanism

One 、 Official explanation

Garbage collection , abbreviation gc. seeing the name of a thing one thinks of its function , It means reuse of waste . If used C Language , So the way to apply for memory is malloc Or is it calloc, And then when you run out of memory , Don't forget to use free Function to release , This is the legendary manual garbage collection , Generally, it's the sweeping monk who uses this way .

that , The most common and traditional in use web In development ,php What is the automatic garbage collection mechanism of ? Let's think about this first , It's just that we all know php yes C The realization of language , Now the C The language is here for you , And then you think about how to use C Language implementation of a variable statistics and release .

PHP There are two core algorithms for memory management : One is reference counting , Second, copy while writing , Please take care of it (bei) Explain (song). When you declare a PHP Variable time ,C Language is at the bottom of the story. It's called zval Of struct( Structure ); If you also assign a value to this variable , such as “hello world”, that C The language is at the bottom. I'll give you another one called zend_value Of union( Consortium ), That's what it looks like on the whole :

Okay , Enter the code combat phase , Pay attention to two points :

  1. With PHP The version is 7.1.17( remember ! This is very important ! Different versions PHP There is a great possibility of different results ! I tried 6 Versions PHP, Three PHP5 edition , Three 7 edition , among PHP7 Version changes are especially frequent , But it doesn't affect the business, and the code won't come out bug, don 't worry ), The operating environment is cli.

  2. The following solution is only for PHP7, No more 5 了 . When you interview , Just need to say 5 I don't know much about ,7 I've seen some of them in depth , The interviewer won't be hard on you .

<?php
$a = 'hello'.mt_rand( 1, 1000 );
echo xdebug_debug_zval('a');
$b = $a;
echo xdebug_debug_zval('a');
$c = $a;
echo xdebug_debug_zval('a');
unset( $c );
echo xdebug_debug_zval('a');

The output is zero :

 Insert picture description here

among ,zval struct The structure is used to hold $a,zend_value union Consortia are used to store data content, that is ’hello916’. Because it is stated later b and c, therefore C I have to make another two for you at the bottom zval struct Structure .

among ,zval and zend value The structure of the system is as follows :( Be careful !!! It's not entirely right PHP zval and zend_value stay C In language struct and union Realization , Just pick out the most important parts and write them out , emphasize : You don't have to recite every word zval and zend_value, You just need to know the principle )

zval {
    
    string "a"            // The name of the variable is a
value  zend_value     // The value of the variable 
type   string         // Variables are of string type 
}
zend_value {
    
    string    "hello916"  // Value content 
refcount  1           // Reference count 
}

See the two above , If the interviewer asks you php Why variables can hold strings "123" It can also save numbers 123, You know what to answer ? Just answer the main point zval There is the type of the variable in , When it's a string 123 When ,type Namely string, here value Point to “123”;

When it's an integer 123 When ,zval Of type by int,value by 123. This is the idea of answering questions , It's important ! and , adopt C All languages are realizable ! Concrete, real val and zend_value The appearance of , Interested students can go online search , If you don't C The foundation of language , Maybe it's hard ! The former is a struct Structure , The latter is a union Consortium !

This refcount It's the reference count in legend , When initializing a The following number of references is 1( Be careful , The right way to say it is a The following array of assignments zend_value The reference count is 1, instead of a This variable zval In itself ).

Then we will $ b = $ a, In fact, it's equivalent to another variable pointing to this zend_value, therefore refcount Turn into 2, The final will be $c = $a, Empathy ,zend_value Of refcount Add... Again 1 Turned into 3. then , We use it unset( $ c ), At the moment ,C All language has to do is put $c Of zval to KO free fall , But it's not free zend_value, At the moment zend_value Of refcount It's a natural decrease 1 become 2 了 .

So what does copy mean when you write ? Look at the code below :

<?php
//  Don't ask why you have to add mt_rand, Otherwise , I can't say the last word , Everywhere pit 
$a = 'hello'.mt_rand( 1, 1000 );
$b = $a;
$a = 123;
echo $b.PHP_EOL;

// Running results , I don't have to tell you. , Toes know it's ’hello’.mt_rand( 1, 1000 ) Result , It can't be 123.
Actually , When you take your $ a Assign a value to $ b When ,$ a The value of is not really copied , This is a great disrespect for memory , It's also a great disrespect for the complexity of time , The computer is just going to $ b Yes $ a It's just the value of , This is called "more fast, better economy" . that , When does replication really happen ? It's when we modify $ a The value of is 123 When , At this time, we have to copy , avoid $ b The value of and $ a The same as .

<?php
$a = 'hello'.mt_rand( 1, 1000 );
$b = $a;
echo xdebug_debug_zval('a');
$a = 'world'.mt_rand( 2, 2000 );
echo xdebug_debug_zval('a');

// The running result is 1, You should be able to sort out the principle yourself
Through a simple case, two key points are explained clearly : Reference counting and copy on write , So it's time for garbage collection . When one zval In being unset When 、 Or run from a function ( It's a local variable ) There are lots of places when you're in the middle of the night , produces zval And zend_value The act of disconnection occurs , This is the time zend What the engine needs to detect is zend_value Of refcount Is it 0, If 0, directly KO free Free up the content .

If zend_value Of recount Not for 0( Nonsense must be greater than 0), This value Can't be released , But it doesn't mean that zend_value It's innocent , Because of this zend_value It could still be rubbish .

What kind of situation will lead to zend_value Of refcount Not for 0, But this zend_value But it's rubbish ?PHP7 There are two situations :

Array :a A member of an array uses & quote a own
object : A member of an object refers to the object itself

<?php
$arr = [ 1 ];
$arr[] = &$arr;
unset( $arr );

In this case ,zend_value It won't release , But we can't let it go , Otherwise, there will be a memory leak , So right now zend_value It's going to be thrown into a place called a garbage dump , then zend The engine will sort these in the garbage collection heap in turn zend_value Do a second test , Check whether it is caused by the above two conditions refcount by 1 But no one really uses it anymore , If it is determined that it is caused by the above two conditions , Then it will zend_value Erase and free memory completely .

So when does garbage collection happen ? Some students may have questions , Namely php It's destroyed after one run , I want it gc What's the use ? Not really , First of all, when fpm After running , Finally, there must be gc Of , The destruction is gc;

The second is , Memory is free on the go , Instead of saving to get the last , You think of a typical scene , A function is used in one of the methods in your controller , Function requires a huge array parameter , Then the function needs to modify this huge array parameter , You should modify the array in the scope of the function , So there will be a copy on write , When the function is finished , You have to release this memory for other processes , Instead of having to wait until local fpm request Destroy it after it's completely completed .

Most of the time : The main reason why the interviewer asks you questions is to ask you a way of thinking , Second, it depends on your level of study . It's like gc This problem , In fact, the garbage collection mechanism of many scripting languages is basically based on the combination of reference counting and copy on write , So if you design a scripting language ,gc The mechanism can be designed according to these two algorithms .

Second, most phper I won't look at these things , The interviewer didn't ask you to memorize so many details , You can't recite it , He still wants to find out if you have a more positive attitude towards deep development .

原网站

版权声明
本文为[Back end regular developers]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202140519024912.html