当前位置:网站首页>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 .
边栏推荐
- How to paste the contents copied by the computer into mobaxterm? How to copy and paste
- 有一个强大又好看的,赛过Typora,阿里开发的语雀编辑器
- Machine learning notes - gray wolf optimization
- 启牛学堂班主任给的证券账户安全吗?能开户吗?
- Photoshop plug-in - action related concepts - actions in non loaded execution action files - PS plug-in development
- 亿咖通科技通过ISO27001与ISO21434安全管理体系认证
- Drive brushless DC motor based on Ti drv10970
- 注意!软件供应链安全挑战持续升级
- 百亿按摩仪蓝海,难出巨头
- I collect multiple Oracle tables at the same time. After collecting for a while, I will report that Oracle's OGA memory is exceeded. Have you encountered it?
猜你喜欢

做研究无人咨询、与学生不交心,UNC助理教授两年教职挣扎史

机器学习笔记 - 灰狼优化

729. 我的日程安排表 I :「模拟」&「线段树(动态开点)」&「分块 + 位运算(分桶)」

1330:【例8.3】最少步数

CPU design related notes

FR练习题目---综合题

Visual task scheduling & drag and drop | scalph data integration based on Apache seatunnel

Behind the ultra clear image quality of NBA Live Broadcast: an in-depth interpretation of Alibaba cloud video cloud "narrowband HD 2.0" technology

微帧科技荣获全球云计算大会“云鼎奖”!

面试突击62:group by 有哪些注意事项?
随机推荐
Drive brushless DC motor based on Ti drv10970
Photoshop插件-动作相关概念-非加载执行动作文件中动作-PS插件开发
我想咨询一下,mysql一个事务对于多张表的更新,怎么保证数据一致性的?
CPU设计实战-第四章实践任务三用前递技术解决相关引发的冲突
Isn't it right to put money into the external market? How can we ensure safety?
危机重重下的企业发展,数字化转型到底是不是企业未来救星
Interpretation of Apache linkage parameters in computing middleware
Change multiple file names with one click
用 Go 跑的更快:使用 Golang 为机器学习服务
实现一个博客系统----使用模板引擎技术
FR练习题目---综合题
How to solve the problem of garbled code when installing dependency through NPM or yarn
C language -- structure and function
I collect multiple Oracle tables at the same time. After collecting for a while, I will report that Oracle's OGA memory is exceeded. Have you encountered it?
一键更改多个文件名字
Microframe technology won the "cloud tripod Award" at the global Cloud Computing Conference!
我这边同时采集多个oracle表,采集一会以后,会报oracle的oga内存超出,大家有没有遇到的?
两个BI开发,3000多张报表?如何做的到?
可视化任务编排&拖拉拽 | Scaleph 基于 Apache SeaTunnel的数据集成
mysql8.0JSON_ Instructions for using contains