当前位置:网站首页>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 .
边栏推荐
- What about SSL certificate errors? Solutions to common SSL certificate errors in browsers
- Postgresql 13 安装
- Photoshop插件-动作相关概念-ActionList-ActionDescriptor-ActionList-动作执行加载调用删除-PS插件开发
- TS所有dom元素的类型声明
- GPS原始坐标转百度地图坐标(纯C代码)
- Crud de MySQL
- 【NVMe2.0b 14-9】NVMe SR-IOV
- Handwriting promise and async await
- Does maxcompute have SQL that can query the current storage capacity (KB) of the table?
- Mongdb learning notes
猜你喜欢
Two Bi development, more than 3000 reports? How to do it?
Machine learning notes - gray wolf optimization
[summary of leetcode weekly competition] the 81st fortnight competition of leetcode (6.25)
爱可可AI前沿推介(7.5)
Topology可视化绘图引擎
用 Go 跑的更快:使用 Golang 为机器学习服务
P6183 [USACO10MAR] The Rock Game S
可视化任务编排&拖拉拽 | Scaleph 基于 Apache SeaTunnel的数据集成
CPU设计相关笔记
Select sort and bubble sort
随机推荐
亿咖通科技通过ISO27001与ISO21434安全管理体系认证
CODING DevSecOps 助力金融企业跑出数字加速度
P1451 求细胞数量/1329:【例8.2】细胞
启牛证券账户怎么开通,开户安全吗?
Talking about how dataset and dataloader call when loading data__ getitem__ () function
webRTC SDP mslabel lable
Selection and use of bceloss, crossentropyloss, sigmoid, etc. in pytorch classification
1330:【例8.3】最少步数
【C 题集】of Ⅷ
Install and configure Jenkins
Crud de MySQL
FR练习题目---简单题
anaconda使用中科大源
黑马程序员-软件测试-10阶段2-linux和数据库-44-57为什么学习数据库,数据库分类关系型数据库的说明Navicat操作数据的说明,Navicat操作数据库连接说明,Navicat的基本使用,
Explain Vue's plan to clean up keepalive cache in time
PyTorch二分类时BCELoss,CrossEntropyLoss,Sigmoid等的选择和使用
Anaconda uses China University of science and technology source
如何将电脑复制的内容粘贴进MobaXterm?如何复制粘贴
Brief introduction of machine learning framework
CPU design practice - Chapter 4 practice task 3 use pre delivery technology to solve conflicts caused by related issues