编写快速高效的JavaScript代码Word文件下载.docx
《编写快速高效的JavaScript代码Word文件下载.docx》由会员分享,可在线阅读,更多相关《编写快速高效的JavaScript代码Word文件下载.docx(38页珍藏版)》请在冰豆网上搜索。
lllovetheSmashingeBookLibrary.GetimmediateaccesstoallSmashingeBookswith70%discountandvoteonthetopicsyou’dliketolearnmoreabout.We’llprepareeBooksthatfityourneedsbest!
Subscribenow!
)
So,HowDoesJavaScriptWorkInV8?
Whileit’spossibletodeveloplarge-scaleapplicationswithoutathoroughunderstandingofJavaScriptengines,anycarownerwilltellyouthey’velookedunderthehoodatleastonce.AsChromeismybrowserofchoice,I’mgoingtotalkalittleaboutitsJavaScriptengine.V8ismadeupofafewcorepieces.
∙Abasecompiler,whichparsesyourJavaScriptandgeneratesnativemachinecodebeforeitisexecuted,ratherthanexecutingbytecodeorsimplyinterpretingit.Thiscodeisinitiallynothighlyoptimized.
∙V8representsyourobjectsinanobjectmodel.ObjectsarerepresentedasassociativearraysinJavaScript,butinV8theyarerepresentedwithhiddenclasses,whichareaninternaltypesystemforoptimizedlookups.
∙Theruntimeprofilermonitorsthesystembeingrunandidentifies“hot”functions(i.e.codethatendsupspendingalongtimerunning).
∙Anoptimizingcompilerrecompilesandoptimizesthe“hot”codeidentifiedbytheruntimeprofiler,andperformsoptimizationssuchasinlining(i.e.replacingafunctioncallsitewiththebodyofthecallee).
∙V8supportsdeoptimization,meaningtheoptimizingcompilercanbailoutofcodegeneratedifitdiscoversthatsomeoftheassumptionsitmadeabouttheoptimizedcodeweretoooptimistic.
∙Ithasagarbagecollector.UnderstandinghowitworkscanbejustasimportantastheoptimizedJavaScript.
GarbageCollection
Garbagecollectionisaformofmemorymanagement.It’swherewehavethenotionofacollectorwhichattemptstoreclaimmemoryoccupiedbyobjectsthatarenolongerbeingused.Inagarbage-collectedlanguagesuchasJavaScript,objectsthatarestillreferencedbyyourapplicationarenotcleanedup.
Manuallyde-referencingobjectsisnotnecessaryinmostcases.Bysimplyputtingthevariableswheretheyneedtobe(ideally,aslocalaspossible,i.e.insidethefunctionwheretheyareusedversusanouterscope),thingsshouldjustwork.
Garbagecollectionattemptstoreclaimmemory.Imagesource:
ValtteriMä
ki.
It’snotpossibletoforcegarbagecollectioninJavaScript.Youwouldn’twanttodothis,becausethegarbagecollectionprocessiscontrolledbytheruntime,anditgenerallyknowsbestwhenthingsshouldbecleanedup.
DE-REFERENCINGMISCONCEPTIONS
InquiteafewdiscussionsonlineaboutreclaimingmemoryinJavaScript,thedeletekeywordisbroughtup,asalthoughitwassupposedtobeusedforjustremovingkeysfromamap,somedevelopersthinkyoucanforcede-referencingusingit.Avoidusingdeleteifyoucan.Inthebelowexample,deleteo.xdoesalotmoreharmthangoodbehindthescenes,asitchangeso‘shiddenclassandmakesitagenericslowobject.
1
varo={x:
1};
2
deleteo.x;
//true
3
o.x;
//undefined
Thatsaid,youarealmostcertaintofindreferencestodeleteinmanypopularJavaScriptlibraries–itdoeshaveapurposeinthelanguage.Themaintakeawayhereistoavoidmodifyingthestructureofhotobjectsatruntime.JavaScriptenginescandetectsuch“hot”objectsandattempttooptimizethem.Thisiseasieriftheobject’sstructuredoesn’theavilychangeoveritslifetimeanddeletecantriggersuchchanges.
Therearealsomisconceptionsabouthownullworks.Settinganobjectreferencetonulldoesn’t“null”theobject.Itsetstheobjectreferencetonull.Usingo.x=nullisbetterthanusingdelete,butit’sprobablynotevennecessary.
o=null;
o;
//null
4
o.x//TypeError
Ifthisreferencewasthelastreferencetotheobject,theobjectistheneligibleforgarbagecollection.Ifthereferencewasnotthelastreferencetotheobject,theobjectisreachableandwillnotbegarbagecollected.
Anotherimportantnotetobeawareofisthatglobalvariablesarenotcleanedupbythegarbagecollectorduringthelifeofyourpage.Regardlessofhowlongthepageisopen,variablesscopedtotheJavaScriptruntimeglobalobjectwillstickaround.
varmyGlobalNamespace={};
Globalsarecleanedupwhenyourefreshthepage,navigatetoadifferentpage,closetabsorexityourbrowser.Function-scopedvariablesgetcleanedupwhenavariablefallsoutofscope.Whenfunctionshaveexitedandtherearen’tanymorereferencestoit,thevariablegetscleanedup.
RULESOFTHUMB
Togivethegarbagecollectorachancetocollectasmanyobjectsaspossibleasearlyaspossible,don’tholdontoobjectsyounolongerneed.Thismostlyhappensautomatically;
hereareafewthingstokeepinmind.
∙Asmentionedearlier,abetteralternativetomanualde-referencingistousevariableswithanappropriatescope.I.e.insteadofaglobalvariablethat’snulledout,justuseafunction-localvariablethatgoesoutofscopewhenit’snolongerneeded.Thismeanscleanercodewithlesstoworryabout.
∙Ensurethatyou’reunbindingeventlistenerswheretheyarenolongerrequired,especiallywhentheDOMobjectsthey’reboundtoareabouttoberemoved
∙Ifyou’reusingadatacachelocally,makesuretocleanthatcacheoruseanagingmechanismtoavoidlargechunksofdatabeingstoredthatyou’reunlikelytoreuse
FUNCTIONS
Next,let’slookatfunctions.Aswe’vealreadysaid,garbagecollectionworksbyreclaimingblocksofmemory(objects)whicharenolongerreachable.Tobetterillustratethis,herearesomeexamples.
functionfoo(){
varbar=newLargeObject();
bar.someCall();
}
Whenfooreturns,theobjectwhichbarpointstoisautomaticallyavailableforgarbagecollection,becausethereisnothingleftthathasareferencetoit.
Comparethisto:
returnbar;
5
6
7
//somewhereelse
8
varb=foo();
Wenowhaveareferencetotheobjectwhichsurvivesthecallandpersistsuntilthecallerassignssomethingelsetob(orbgoesoutofscope).
CLOSURES
Whenyouseeafunctionthatreturnsaninnerfunction,thatinnerfunctionwillhaveaccesstotheouterscopeevenaftertheouterfunctionisexecuted.Thisisbasicallyaclosure—anexpressionwhichcanworkwithvariablessetwithinaspecificcontext.Forexample:
01
functionsum(x){
02
functionsumIt(y){
03
returnx+y;
04
};
05
returnsumIt;
06
07
08
//Usage
09
varsumA=sum(4);
10
varsumB=sumA(3);
11
console.log(sumB);
//Returns7
Thefunctionobjectcreatedwithintheexecutioncontextofthecalltosumcan’tbegarbagecollected,asit’sreferencedbyaglobalvariableandisstillverymuchaccessible.ItcanstillbeexecutedviasumA(n).
Let’slookatanotherexample.Here,canweaccesslargeStr?
vara=function(){
varlargeStr=newArray(1000000).join('
x'
);
returnfunction(){
returnlargeStr;
}();
Yes,wecan,viaa(),soit’snotcollected.Howaboutthisone?
varsmallStr='
;
returnfunction(n){
returnsmallStr;
Wecan’taccessitanymoreandit’sacandidateforgarbagecollection.
TIMERS
Oneoftheworstplacestoleakisinaloop,orinsetTimeout()/setInterval(),butthisisquitecommon.
Considerthefollowingexample.
varmyObj={
callMeMaybe:
function(){
varmyRef=this;
varval=setTimeout(function(){
console.log('
Timeisrunningout!
'
myRef.callMeMaybe();
},1000);
}
9
};
Ifwethenrun:
myObj.callMeMaybe();
tobeginthetimer,wecanseeeverysecond“Timeisrunningout!
”Ifwethenrun:
myObj=null;
Thetimerwillstillfire.myObjwon’tbegarbagecollectedastheclosurepassedtosetTimeouthastobekeptaliveinordertobeexecuted.Inturn,itholdsreferencestomyObjasitcapturesmyRef.Thiswouldbethesameifwe’dpassedtheclosuretoanyotherfunction,keepingreferencestoit.
Itisalsoworthkeepinginmindthatr