当前位置:网站首页>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】
Catalog
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 :
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.
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 :
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 .
边栏推荐
- Mongdb learning notes
- How to choose the appropriate certificate brand when applying for code signing certificate?
- webRTC SDP mslabel lable
- 注意!软件供应链安全挑战持续升级
- Fr exercise topic - simple question
- Photoshop插件-动作相关概念-ActionList-ActionDescriptor-ActionList-动作执行加载调用删除-PS插件开发
- 市值蒸发超百亿美元,“全球IoT云平台第一股”赴港求生
- 亿咖通科技通过ISO27001与ISO21434安全管理体系认证
- 【招聘岗位】基础设施软件开发人员
- C language -- structure and function
猜你喜欢
30岁汇源,要换新主人了
Visual task scheduling & drag and drop | scalph data integration based on Apache seatunnel
Dark horse programmer - software testing -10 stage 2-linux and database -44-57 why learn database, description of database classification relational database, description of Navicat operation data, de
Behind the ultra clear image quality of NBA Live Broadcast: an in-depth interpretation of Alibaba cloud video cloud "narrowband HD 2.0" technology
How to choose the appropriate certificate brand when applying for code signing certificate?
超越PaLM!北大硕士提出DiVeRSe,全面刷新NLP推理排行榜
爱可可AI前沿推介(7.5)
729. 我的日程安排表 I :「模拟」&「线段树(动态开点)」&「分块 + 位运算(分桶)」
[detailed explanation of Huawei machine test] character statistics and rearrangement
Drive brushless DC motor based on Ti drv10970
随机推荐
如何将电脑复制的内容粘贴进MobaXterm?如何复制粘贴
爱可可AI前沿推介(7.5)
Pointer operation - C language
我这边同时采集多个oracle表,采集一会以后,会报oracle的oga内存超出,大家有没有遇到的?
Interview shock 62: what are the precautions for group by?
PostgreSQL 13 installation
Run faster with go: use golang to serve machine learning
Type declaration of all DOM elements in TS
一键更改多个文件名字
Does maxcompute have SQL that can query the current storage capacity (KB) of the table?
Coding devsecops helps financial enterprises run out of digital acceleration
Crud de MySQL
How to choose the appropriate certificate brand when applying for code signing certificate?
想进阿里必须啃透的12道MySQL面试题
CPU design practice - Chapter 4 practical task 2 using blocking technology to solve conflicts caused by related problems
[recruitment position] infrastructure software developer
【NVMe2.0b 14-9】NVMe SR-IOV
可转债打新在哪里操作开户是更安全可靠的呢
How can I quickly check whether there is an error after FreeSurfer runs Recon all—— Core command tail redirection
百亿按摩仪蓝海,难出巨头