PHP的垃圾回收机制

2022-08-05sad creeper

一、引用计数基础知识

  • 每个php变量存在一个叫 zval 的变量容器中。
  • 一个 zval 变量容器,除了包含变量的类型和值,还包括两个字节的额外信息。
  • 第一个是 is_ref,是个bool值,用来标识这个变量是否是属于引用集合。通过这个字节,php引擎才能把普通变量和引用变量区分开来,由于php允许用户通过使用&来使用自定义引用,zval变量容器中还有一个内部引用计数机制,来优化内存使用。
  • 第二个额外字节是 refcount,用以表示指向这个zval变量容器的变量个数。
  • 所有的符号存在一个符号表中,其中每个符号都有作用域(scope),那些主脚本(比如:通过浏览器请求的的脚本)和每个函数或者方法也都有作用域。


二、生成zval容器

  • 当一个变量被赋常量值时,就会生成一个zval变量容器
  • 如果安装了Xdebug,则可以通过 xdebug_debug_zval() 查看这两个值
<?php$a = "new string";xdebug_debug_zval('a'); //结果a: (refcount=1, is_ref=0)='new string'


三、增加zval的引用计数

把一个变量赋值给另一变量将增加引用次数

<?php$a = "new string";$b = $a;xdebug_debug_zval( 'a' ); //结果a: (refcount=2, is_ref=0)='new string'


四、减少zval引用计数

  • 使用 unset() 可以减少引用次数 
  • 包含类型和值的这个变量容器就会从内存中删除
<?php$a = "new string";$c = $b = $a;xdebug_debug_zval( 'a' );unset( $b, $c );xdebug_debug_zval( 'a' ); //结果a: (refcount=3, is_ref=0)='new string'a: (refcount=1, is_ref=0)='new string'


五、复合类型的zval容器

  • 与 标量(scalar)类型的值不同
  • array和 object类型的变量把它们的成员或属性存在自己的符号表中
  • 这意味着下面的例子将生成三个zval变量容器
  • 这三个zval变量容器是: a,meaning和 number
<?php$a = array( 'meaning' => 'life', 'number' => 42 );xdebug_debug_zval( 'a' ); //结果a: (refcount=1, is_ref=0)=array (   'meaning' => (refcount=1, is_ref=0)='life',   'number' => (refcount=1, is_ref=0)=42)


六、增加复合类型的引用计数

添加一个已经存在的元素到数组中

<?php$a = array( 'meaning' => 'life', 'number' => 42 );$a['life'] = $a['meaning'];xdebug_debug_zval( 'a' ); //结果a: (refcount=1, is_ref=0)=array (   'meaning' => (refcount=2, is_ref=0)='life',   'number' => (refcount=1, is_ref=0)=42,   'life' => (refcount=2, is_ref=0)='life')


七、减少复合类型的引用计数

  • 删除数组中的一个元素
  • 就是类似于从作用域中删除一个变量.
  • 删除后,数组中的这个元素所在的容器的“refcount”值减少
<?php$a = array( 'meaning' => 'life', 'number' => 42 );$a['life'] = $a['meaning'];unset( $a['meaning'], $a['number'] );xdebug_debug_zval( 'a' ); //结果a: (refcount=1, is_ref=0)=array (   'life' => (refcount=1, is_ref=0)='life')


八、特殊情况

当我们添加一个数组本身作为这个数组的元素时,事情就变得有趣 

同上,对一个变量调用unset,将删除这个符号,且它指向的变量容器中的引用次数也减1

<?php$a = array( 'one' );$a[] = &$a;xdebug_debug_zval( 'a' ); //结果a: (refcount=2, is_ref=1)=array (   0 => (refcount=1, is_ref=0)='one',   1 => (refcount=2, is_ref=1)=...)


九、清理变量容器的问题

尽管不再有某个作用域中的任何符号指向这个结构(就是变量容器),由于数组元素“1”仍然指向数组本身,所以这个容器不能被清除 。

因为没有另外的符号指向它,用户没有办法清除这个结构,结果就会导致内存泄漏。

庆幸的是,php将在脚本执行结束时清除这个数据结构,但是在php清除之前,将耗费不少内存。

如果上面的情况发生仅仅一两次倒没什么,但是如果出现几千次,甚至几十万次的内存泄漏,这显然是个大问题


十、回收周期

像以前的 php 用到的引用计数内存机制,无法处理循环的引用内存泄漏

而在php 5.3.0 中使用同步算法,来处理这个内存泄漏问题

如果一个引用计数增加,它将继续被使用,当然就不再在垃圾中。

如果引用计数减少到零,所在变量容器将被清除(free)

就是说,仅仅在引用计数减少到非零值时,才会产生垃圾周期

在一个垃圾周期中,通过检查引用计数是否减1,并且检查哪些变量容器的引用次数是零,来发现哪部分是垃圾


十一、回收算法分析

  • 为避免不得不检查所有引用计数可能减少的垃圾周期
  • 这个算法把所有可能根(possible roots 都是zval变量容器),放在根缓冲区(root buffer)中(用紫色来标记,称为疑似垃圾),这样可以同时确保每个可能的垃圾根(possible garbage root)在缓冲区中只出现一次。仅仅在根缓冲区满了时,才对缓冲区内部所有不同的变量容器执行垃圾回收操作。看上图的步骤 A。
  • 在步骤 B 中,模拟删除每个紫色变量。模拟删除时可能将不是紫色的普通变量引用数减"1",如果某个普通变量引用计数变成0了,就对这个普通变量再做一次模拟删除。每个变量只能被模拟删除一次,模拟删除后标记为灰
  • 在步骤 C 中,模拟恢复每个紫色变量。恢复是有条件的,当变量的引用计数大于0时才对其做模拟恢复。同样每个变量只能恢复一次,恢复后标记为黑,基本就是步骤 B 的逆运算。这样剩下的一堆没能恢复的就是该删除的蓝色节点了,在步骤 D 中遍历出来真的删除掉


十二、性能考虑

主要有两个领域对性能有影响

第一个是内存占用空间的节省

另一个是垃圾回收机制释放已泄漏的内存耗费的时间增加


十三、垃圾回收机制的结论

PHP中的垃圾回收机制,仅仅在循环回收算法确实运行时会有时间消耗上的增加。但是在平常的(更小的)脚本中应根本就没有性能影响。

然而,在平常脚本中有循环回收机制运行的情况下,内存的节省将允许更多这种脚本同时运行在你的服务器上。因为总共使用的内存没达到上限。

这种好处在长时间运行脚本中尤其明显,诸如长时间的测试套件或者daemon脚本此类。


转载至:https://mp.weixin.qq.com/s/aoP3X5LAvIwWhFWZdxK_lQ

阅读 2349 评论


h

http

Normally I do not learn article on blogs, however I wish to say that this write-up very forced me to take a look at and do it! Your writing style has been surprised me. Thanks, quite nice article.

2周前 ·


h

http://mozillabd.science

is hgh bad for you

2周前 ·


f

f1news.site

hgh dosage

2周前 ·


s

schoolido.lu

is 4 units of hgh a day bad

2周前 ·


h

https://jobgetr.com/members/facthot79/activity/315253

hgh erfahrung bodybuilding

2周前 ·


k

kanban.xsitepool.tu-freiberg.de

hgh anti aging dosage

2周前 ·


h

https://diego-maradona.Com.az

hgh wirkungseintritt bodybuilding

2周前 ·


j

jobgetr.com

hgh injection

2周前 ·


0

09Vodostok.ru

wieviel mg ist eine einheit hgh

2周前 ·


t

travelersqa.com

hgh bodybuilding dosierung

2周前 ·


a

atavi.com

hgh vor dem schlafen

2周前 ·


h

https://forum.issabel.org/

hgh bivirkninger

2周前 ·


e

everydayfam.com

hgh day

2周前 ·


h

https://matkafasi.com/

genfx hgh

2周前 ·


e

escatter11.fullerton.edu

hgh injektion

2周前 ·


s

support.roombird.ru

is hgh better than testosterone

2周前 ·


k

king-wifi.win

was ist hgh bodybuilding

2周前 ·


H

Https://forum.lexulous.com/

2 einheiten hgh am tag

2周前 ·


m

md.swk-web.com

hgh vs dbol

2周前 ·


F

Flibustier.top

hgh cycle dosage bodybuilding

2周前 ·


p

peatix.com

crazybulk hgh-x2 review

2周前 ·


h

https://posteezy.com/hormone-de-croissance-Hgh-vendre-achat-en-ligne-en-france-prix-et-injections

ciclo hgh

2周前 ·


h

https://play.ntop.tv/user/Rulebubble08/

is hgh the same as testosterone

2周前 ·


s

stackoverflow.qastan.be

hgh cycle for beginners

2周前 ·


a

adair-sexton-3.hubstack.net

hgh for fat loss bodybuilding

2周前 ·


w

www.generation-N.at

hgh bodybuilding kaufen

2周前 ·


a

avtovoprosi.ru

was ist hgh bodybuilding

2周前 ·


h

https://iotpractitioner.com/

hgh wirkung bodybuilding

2周前 ·


h

https://masajeseroticostarragona.com/author/sizeself16

how long to cycle hgh

2周前 ·


H

Http://lideritv.ge/user/walkberet89/

hgh erhöhen

2周前 ·


h

https://may22.ru/

hgh 1 iu per day results

2周前 ·


h

https://pad.geolab.space/wS-WNt7vQXeTMO90EI9U-A

how much hgh

2周前 ·


h

https://www.Giveawayoftheday.com

hgh cutting cycle

2周前 ·


a

atavi.Com

hgh before and after pics

3周前 ·


h

https://hedgedoc.eclair.ec-lyon.fr/

3 iu hgh

3周前 ·


f

firsturl.de

hgh fettverbrennung

3周前 ·


h

https://md.entropia.de

hgh cycle length

3周前 ·


h

https://may22.ru/user/shoehyena20/

hgh daily dosage for bodybuilding

3周前 ·


f

forum.issabel.org

hgh vs testosterone for fat loss

3周前 ·


m

monjournal.xyz

stacking steroids

3周前 ·


p

pad.stuve.de

bodybuilding hgh dose

3周前 ·


h

http://king-wifi.win//index.php?title=hwangalbright1882

negative side effects of hgh

3周前 ·


m

mcforces.ru

testosterone chemical structure

3周前 ·


f

fkwiki.win

inject steroids

3周前 ·


p

postheaven.net

hgh results timeline

3周前 ·


w

wehrle

how much hgh to inject

3周前 ·


P

Pad.karuka.tech

hgh bodybuilding dose

3周前 ·


A

Anvarol: Real Gains or Fake Claims

The problem here is that what you suppose is Primobolan could be a totally different steroid, and even worse, it might contain dangerous elements that do little greater than trigger negative unwanted effects. The presence of an entirely completely different hormone in the components can radically alter the steroid’s potency. The unlucky reality that the product you obtain could also be totally totally different from what you consider it to be can also have a unfavorable impact on the way you view the strength of a steroid. Obtaining the real elements for this steroid could be fairly difficult, and it has turn into a very costly steroid due to this. Age is an effective instance of this, as most men endure a 1% or so drop in testosterone each year after 30. This task becomes tougher in forensic settings where an individual reviews AAS use at the time of against the law dedicated months or even years earlier. If by probability routine laboratory exams were carried out at the moment, a few of the abnormalities listed above could also be found. A variety of hypotheses to explain AAS dependence have been put ahead [47, 48] and proposals for treating what has been described as steroid ‘abuse’ or dependence have long been proposed [49–51]. The undesirable results arising from anabolic steroid administration (Table 3) have been extensively reviewed (Haupt and Rovere, 1984; Di Pasquale, 1990; Graham and Kennedy, 1990; Landry and Primos, 1990; Shahidi, 2001; Kicman and Gower, 2003b; James and Kicman, 2004). Parenteral preparations do not require a 17α-alkyl group but usually the 17β-hydroxyl group is esterified with an acid moiety (van der Vies, 1993) to prevent rapid absorption from the oily vehicle, usually arachis oil plus a small amount of benzyl alcohol. Once in the circulation, hydrolysis quickly happens by the action of blood esterases to yield the lively compound. The esters embody cyclohexylpropionate, decanoate, laurate and phenylpropionate for nandrolone; acetate, cypionate, decanoate, enanthate, isocaproate, phenylpropionate, propionate and undecanoate for testosterone, undecylenate for boldenone and acetate for trenbolone. This article is based on scientific proof, written by specialists and truth checked by professionals on this field. All Steroidal.com content is medically reviewed and reality checked to ensure as a lot factual accuracy as possible. Many investigators employed the strategy proposed by Hershberger et al. (1953), but some made their own modifications to it, and others nonetheless used the seminal vesicles as a bioassay of androgenicity. This section collects any data citations, knowledge availability statements, or supplementary materials included on this article. Knowledge sharing not relevant, no new knowledge had been created or analyzed in this research. Animal histological research of testes demonstrated spermatogenesis impairment with lack of superior spermatidis and decreased number of spermatidis as a outcome of AAS use [5,88]. An impairment of the blood-testis-barrier was also noticed in CD1 mice treated with ND, which can play a task in triggering the spermatogenesis alteration [103]. Moreover, quantitative modifications in quantity, diameter and thickness of seminiferous tubules had been detected in albino rats after AAS administration [104]. Apoptosis has been reported to play an essential role within the regulation of germ cell populations in the grownup testes. The correlation between apoptosis and excessive AAS doses and workout routines has just lately been experimentally assessed in animal fashions. Shokri et al. report a major enhance within the fee of apoptosis of spermatogenic cells after nandrolone administration, a rise clearly amplified by physical exercise [5]. Nonetheless, TE led to no vital adjustments in MyoD or MSTN mRNA abundances in grownup human males (20). Between-treatment results of MSTN have been 64% decrease with TE administration in rats compared to a sham management (5). TE significantly stimulated IGF1 and MSTN expression in each rats and older male people, with IGF1 expression reaching values fivefold higher in a traditional situation of 10-month-old male fisher 344xF1 Brown Norway rats compared to orchiectomized (ORX) teams (7, 14, 42). However, TE didn't significantly have an result on the total concentrations of MHC isotype mRNA in 18–35-year-old human males relative to different groups (35). There is not any restriction on the possession of these substances when they are a half of a medicinal product and are for self-administration. Nevertheless, prosecutions of intent to provide have been made of people found in possession of large quantities of these substances with no prescription for them. A House Workplace licence is required for importation and exportation of anabolic steroids, except in circumstances of small portions for reliable functions. Ergogenic uses for AAS in sports activities, racing, and bodybuilding as performance-enhancing medicine are controversial due to their adverse results and the potential to achieve benefit in physical competitions. In international locations the place AAS are controlled substances, there could be usually a black market by which smuggled, clandestinely manufactured and even counterfeit medication are bought to customers. Due to its mild androgenic properties, oxandrolone is considered one of the few agents to be routinely abused by feminine athletes. Athletes, from weightlifters to boxers, use oxandrolone, in search of to increase energy with out experiencing extra weight achieve. This AAS is not favored in clinical apply due to its poor anabolic effects, but athletes abuse it for its androgenic nature and lack of peripheral aromatization. Methyltestosterone is a very fundamental anabolic-androgenic steroid (AAS), with the only addition being a methyl group at C-17. This eliminates first-pass degradation in the liver, making oral dosing potential. AASs are medication derived from the modification of the testosterone molecule to find a way to increase or restrict sure traits of testosterone. A bigger proportion of individuals (37%) in their examine reported that less than 12 months had elapsed since AAS cessation. Sixty-two % provided postcycle recovery info; nonetheless, solely 12.5% of the sites provided data or recommendations for non-AAS options. One of the eight sites (12.5%), anabolics.com, provided non-AAS dietary supplements and didn't offer any type of testosterone, synthetic AAS, or ED medicines. Nonetheless, every of their dietary supplements was named synonymously with the well-known synthetic AAS agent for which their supplement mimicked. A consultant example is D-ANABOL 25 composed of rhodiola root powder, fenugreek seed extract, cyanotis vaga extract, inosine, and clary sage leaf extract, permitting categorization as a pure complement by the USFDA.

4周前 ·


m

magiamgia.blog.fc2.com

how to make synthetic testosterone

1个月前 ·


h

https://sostinestauras.lt/events/teida-moteru-tinklinio-lyga/

prednisone for muscle growth

1个月前 ·


w

www.cartergroupland.com

mexico anabolic steroids

1个月前 ·


i

images.google.ms

steroids drug classification

1个月前 ·


h

http://sorucevap.kodmerkezi.net/

before after steroids

1个月前 ·


m

maps.google.hr

best clenbuterol brand

1个月前 ·


b

bookmark4you.win

gnc ripped muscle x

1个月前 ·


h

https://hack.allmende.io

how are steroids dangerous

1个月前 ·


w

www.anibookmark.com

medical uses for steroids

1个月前 ·


i

independent.academia.edu

deca tablets

1个月前 ·


w

www.matesroom.com

best steroid stack for lean muscle mass

1个月前 ·


a

anabolic for sale

steroids ingredients list

2个月前 ·


g

git.rabbittec.com

legal injectable steroids for sale

2个月前 ·


c

cliqq.ru

ipamorelin names

2个月前 ·