...
browser
Garbage Collection in V8
15 min read
Thevisuallagsonscreencanbecausedbyacoupleofreasons.Oneofthereasonsiswhentherearetoomanyobjectsorvariablesinusetokeeptrackof.Thisiswhentheefficiencyofgarbagecollectionistested.Browser’stargetistomaintain60fpsrenderingfortheidealexperienceandgarbage
collectionhelpsachieveit.Idletimeisthewindowduringwhichgarbagecollectiontakesplace.Thisidletimeisthedurationwhenthemainthreadhasnoothertaskssuchasfinishinganongoinganimationorexecutingmicrotasks.It’susuallyinmilliseconds.Garbagecollectoralonedoesnotmakeallthese

decisions.Oneoftheentitiesinvolvedisataskscheduler.Taskschedulerisacentralizedcomponentforjavascriptandrenderingengines.Ifitexpectsatasktofinishin20msanditfinishesin16ms,then4mscanbeusedforotherhighprioritytaskssuchasgarbagecollection.
GarbageCollectionisaprocedurewhenthejsengineremovesthedatathatisnolongergettingusedorwillnotbeused.Forawhilelet’snotthinkabouttheexecutionoftasksintermsofcallstack,queueandeventloop.Considerascenariowherealotofconcurrentandserialactionsaregoing
onlikeanimatingadiv,respondingtoahover,respondingtoscroll,paintingthenextframe.Keepingasimplequeueoftasksdoesn’tmakesenseforthebrowserbecausesometasksholdmoreimportancethantheothers.Forexample,paintingthenextframeonscreenmightbeattheendofthe
queuewhichcanleadtovisualstuttersthushamperingtheexperience.Priorityofeachtaskhastobeconsideredaswell.Forthis,thereisataskscheduler.Itassignsandupdatesthepriorityofeachtask.Priorityofataskalsodependsonthecurrentandexpectedstateofrendering.
IftherearenomorerenderingtasksthenthepriorityofidletaskssuchasGC,prefetching,cachingetc.isincreasedandtheyareaddedinthemainthreadforexecutionbutifthisidletimeendsbeforeexpectedthenprioritieshavetobechangedorrevertedagainsothatcurrenttasks
canbereplacedwithmoreurgenttasks.Idletasksarelowprioritytasksthatarepickedupforexecutionduringtheidletime.Thisidletimeispredictedbasedonthestateofallthecomponentslikejsengine,renderingengine,gpuengine,mediaengine,storageengine,securityengineetc.
involvedintheprocessofrunningawebapp.Agenerationalgarbagecollectorisoneofthetypeswhichisusedtoexecutethecollection.Thistypeofgarbagecollectordividestheheapmemoryintodifferentpartsandassignsthevariablesordataaccordingtotheirage.Orinocoisonesuchcollectorandisusedbyv8.Byassigning,
Imeaneachpartwillholdareferencetotheobjectthatbelongstothem.Itmainlydividesthememoryintotwospaces-younggenerationandoldgeneration.Theyounggenerationisfurtherdividedinto-NurseryandIntermediate.Anyobjectthatiscreatedisfirstassignedtotheyoung...

generation’snursery.Ifitstaysinuseduringthenextgarbagecollectionthenitismovedtoahighergenerationspace.Thiswayitcanperformfrequentcollectiononyoungobjectswithshortlivesandlonglivingobjectscanbecollectedafterlongerintervals.Thesecyclesofgarbagecollection
foryounggenerationobjectsarecalledscavenges.Thetheorysaysthatasignificantamountofmemorycanbefreedbycollectingobjectsthatareshortlived.
Oneofthewaystodosoisbymarkandsweepalgorithm.OilpanisalibrarythatusesthisalgorithmandisusedalongsideOrinoco.Imagineatreeofallvariablescurrentlyinuse,therootnodeistheglobalcontextandfromthere,basedonthenestedcontextsorscopes(Iknowbotharenotthesame),therearechildnodesofvariables.
Itcanalsobeagraphinsteadofatreeaswellbutwhat’simportantisthatthegarbagecollectortraversesthisnetworkandmarkseachobject.Theninthenextstep,itgoesintotheheapmemoryandtracksalltheobjectsthatwerenotmarkedearlieranddrawstheconclusionthatsincethese
selectedobjectsarenotmarked,theyarenotgettingusedanymore.MarkandSweep.Asthiscanbeatimetakingtask,itisnotdoneinonegobutincrementally.Everycycleofthistaskhasadeadlinetomeettokeeptherenderinglatencyatminimum.Earlier,v8usedtoperformthesetasks
incrementallyonthemainthreadbutasobjectgraphsgrewinsize,anewapproachwasintroducedcalledconcurrentsweeping,whichuseshelperthreadsforoffloadingthesetasksinthebackgroundwhilethemainthreadcanperformothertasks.
Astheheapmemoryisdividedforeachgeneration,thegarbagecollectorkeepstrackofeachoftheirmemorylimits.Iftheyounggeneration’sheaplimitisabouttobemaxedoutthenitwillprioritizeyounggenenerationscavenges.Whereasiftherehavebeenfrequentyounggenerationscavengesand
notenoughvariableswerediscardedthenitmeanstheobjectsneedmoretimetogooutofuse,thereforethepriorityofthenextscavengecanbedecreasedsothatbythetimeitisscheduled,enoughvariableswouldhavediedandtheiroccupiedmemorycouldbefreed.Similarly,iftheoldgeneration’s...

heapisabouttobemaxedoutthenitwillprioritizemarkandsweepworkerthreads.Withtimechangesweremadeinthewaythesetasksareexecuted.Thiswholeprocessnowcaneitherbedoneincrementallyonthemainthreadorconcurrentlybyusinghelperthreads.Asajavascriptdeveloper,garbagecollectioncannotbecontrolledexplicitlybuttherearesurelysome
waystohelpit.Upuntilnow,onethingcanbeclearlyconcludedthatthemorethenumberofvariablesthatarestillinuse,thelesswillbethememoryfreedaftercollectionandmostofthememoryfreedisfromtheshortlivedvariables.Thehigherthescopeofthevariable,thelongeritwill
live.Globalvariablesaremaintainedforthewholedurationofruntime.Consideringthescopeneededforavariableduringdevelopmentwillprovetobehelpfulduringgarbagecollection.Cleanupfunctionsinreactcomponents,removingsubscriptionsandeventlisteners,timeoutsandintervals,all
helpindiscardingthedeadobjects.Storingirrelevantdataasastateofthecomponentisnotrightasstatesaremaintainedaslongasthecomponentexists.Bifurcationofcomponentsintosmallonescanhelpaswell,thiswillreduceDOMnodesandjavascript.Listvirtualizationforlongerlists.
EventhoughDOMnodesarenotapartofjavascriptparsingandjavascriptengine,theirreferencesarestoredintheheapusedbythejavascriptengine.IftherearetoomanyDOMnodes,thentheirreferenceswilloccupymostoftheheap.Progressivehydration,codesplitting,lazyloading,allthesetechniquesnotonlyworkasprecautionsbutalsoasthecure.