计算机科学与技术 外文翻译 外文文献 英文文献 提高字符串处理性能的应用程序Word下载.docx
《计算机科学与技术 外文翻译 外文文献 英文文献 提高字符串处理性能的应用程序Word下载.docx》由会员分享,可在线阅读,更多相关《计算机科学与技术 外文翻译 外文文献 英文文献 提高字符串处理性能的应用程序Word下载.docx(28页珍藏版)》请在冰点文库上搜索。
Summary:
MostActiveServerPages(ASP)applicationsrelyonstringconcatenationtobuildHTML-formatteddatathatisthenpresentedtousers.ThisarticlecontainsacomparisonofseveralwaystocreatethisHTMLdatastream,someofwhichprovidebetterperformancethanothersforagivensituation.AreasonableknowledgeofASPandVisualBasicprogrammingisassumed.(11printedpages)
Contents
Introduction
ASPDesign
StringConcatenation
TheQuickandEasySolution
TheStringBuilder
TheBuilt-inMethod
Testing
Results
Conclusion
WhenwritingASPpages,thedeveloperisreallyjustcreatingastreamofformattedtextthatiswrittentotheWebclientviatheResponseobjectprovidedbyASP.YoucanbuildthistextstreaminseveraldifferentwaysandthemethodyouchoosecanhavealargeimpactonboththeperformanceandthescalabilityoftheWebapplication.OnnumerousoccasionsinwhichIhavehelpedcustomerswithperformance-tuningtheirWebapplications,IhavefoundthatoneofthemajorwinshascomefromchangingthewaythattheHTMLstreamiscreated.InthisarticleIwillshowafewofthecommontechniquesandtestwhateffecttheyhaveontheperformanceofasimpleASPpage.
ManyASPdevelopershavefollowedgoodsoftwareengineeringprinciplesandmodularizedtheircodewhereverpossible.Thisdesignnormallytakestheformofanumberofincludefilesthatcontainfunctionsmodelingparticulardiscretesectionsofapage.Thestringoutputsfromthesefunctions,usuallyHTMLtablecode,canthenbeusedinvariouscombinationstobuildacompletepage.SomedevelopershavetakenthisastagefurtherandmovedtheseHTMLfunctionsintoVisualBasicCOMcomponents,hopingtobenefitfromtheextraperformancethatcompiledcodecanoffer.
Althoughthisiscertainlyagooddesignpractice,themethodusedtobuildthestringsthatformthesediscreteHTMLcodecomponentscanhavealargebearingonhowwelltheWebsiteperformsandscales—regardlessofwhethertheactualoperationisperformedfromwithinanASPincludefileoraVisualBasicCOMcomponent.
ConsiderthefollowingcodefragmenttakenfromafunctioncalledWriteHTML.TheparameternamedDataissimplyanarrayofstringscontainingsomedatathatneedstobeformattedintoatablestructure(datareturnedfromadatabase,forinstance).
CopyCode
FunctionWriteHTML(Data)
DimnRep
FornRep=0to99
sHTML=sHTML&
vbcrlf_
&
"
<
TR>
TD>
"
(nRep+1)&
/TD>
_
Data(0,nRep)&
Data(1,nRep)&
Data(2,nRep)&
Data(3,nRep)&
Data(4,nRep)&
Data(5,nRep)&
/TR>
Next
WriteHTML=sHTML
EndFunction
ThisistypicalofhowmanyASPandVisualBasicdevelopersbuildHTMLcode.ThetextcontainedinthesHTMLvariableisreturnedtothecallingcodeandthenwrittentotheclientusingResponse.Write.Ofcourse,thiscouldalsobeexpressedassimilarcodeembeddeddirectlywithinthepagewithouttheindirectionoftheWriteHTMLfunction.TheproblemwiththiscodeliesinthefactthatthestringdatatypeusedbyASPandVisualBasic,theBSTRorBasicString,cannotactuallychangelength.Thismeansthateverytimethelengthofthestringischanged,theoriginalrepresentationofthestringinmemoryisdestroyed,andanewoneiscreatedcontainingthenewstringdata:
thisresultsinamemoryallocationoperationandamemoryde-allocationoperation.Ofcourse,inASPandVisualBasicthisisalltakencareofforyou,sothetruecostisnotimmediatelyapparent.Allocatingandde-allocatingmemoryrequirestheunderlyingruntimecodetotakeoutexclusivelocksandthereforecanbeexpensive.Thisisespeciallyapparentwhenstringsgetbigandlargeblocksofmemoryarebeingallocatedandde-allocatedinquicksuccession,ashappensduringheavystringconcatenation.Whilethismaypresentnomajorproblemsinasingleuserenvironment,itcancauseseriousperformanceandscalabilityissueswhenusedinaserverenvironmentsuchasinanASPapplicationrunningonaWebserver.
Sobacktothecodefragmentabove:
howmanystringallocationsarebeingperformedhere?
Infacttheansweris16.Inthissituationeveryapplicationofthe'
&
'
operatorcausesthestringpointedtobythevariablesHTMLtobedestroyedandrecreated.Ihavealreadymentionedthatstringallocationisexpensive,becomingincreasinglymoresoasthestringgrows;
armedwiththisknowledge,wecanimproveuponthecodeabove.
Therearetwowaystomitigatetheeffectofstringconcatenations,thefirstistotryanddecreasethesizeofthestringsbeingmanipulatedandthesecondistotryandreducethenumberofstringallocationoperationsbeingperformed.LookattherevisedversionoftheWriteHTMLcodeshownbelow.
(vbcrlf_
)
Atfirstglanceitmaybedifficulttospotthedifferencebetweenthispieceofcodeandtheprevioussample.ThisonesimplyhastheadditionofparenthesesaroundeverythingaftersHTML=sHTML&
.Thisactuallyreducesthesizeofstringsbeingmanipulatedinmostofthestringconcatenationoperationsbychangingtheorderofprecedence.IntheoriginalcodesampletheASPcomplierwilllookattheexpressiontotherightoftheequalssignandjustevaluateitfromlefttoright.Thisresultsin16concatenationoperationsperiterationinvolvingsHTMLwhichisgrowingallthetime.Inthenewversionwearegivingthecompilerahintbychangingtheorderinwhichitshouldcarryouttheoperations.Nowitwillevaluatetheexpressionfromlefttorightbutalsoinsideout,i.e.insidetheparenthesesfirst.Thistechniqueresultsin15concatenationoperationsperiterationinvolvingsmallerstringswhicharenotgrowingandonlyonewiththelarge,andgrowing,sHTML.Figure1showsanimpressionofthememoryusagepatternsofthisoptimizationagainstthestandardconcatenationmethod.
Figure1
Comparisonofmemoryusagepatternbetweenstandardandparenthesizedconcatenation
Usingparenthesescanmakequiteamarkeddifferenceinperformanceandscalabilityincertaincircumstances,asIwilldemonstratelaterinthisarticle.
Wehaveseenthequickandeasysolutiontothestringconcatenationproblem,andformanysituationsthismayprovidethebesttrade-offbetweenperformanceandefforttoimplement.Ifwewanttogetseriousaboutimprovingtheperformanceofbuildinglargestrings,however,thenweneedtotakethesecondalternative,whichistocutdownthenumberofstringallocationoperations.InordertoachievethisaStringBuilderisrequired.Thisisaclassthatmaintainsaconfigurablestringbufferandmanagesinsertionsofnewpiecesoftextintothatbuffer,causingstringreallocationonlywhenthelengthofthetextexceedsthelengthofthestringbuffer.TheMicrosoft.NETframeworkprovidessuchaclassforfree(System.Text.StringBuilder)thatisrecommendedforallstringconcatenationoperationsinthatenvironment.IntheASPandclassicVisualBasicworldwedonothaveaccesstothisclass,soweneedtobuildourown.BelowisasampleStringBuilderclasscreatedusingVisualBasic6.0(error-handlingcodehasbeenomittedintheinterestofbrevity).
OptionExplicit
defaultinitialsizeofbufferandgrowthfactor
PrivateConstDEF_INITIALSIZEAsLong=1000
PrivateConstDEF_GROWTHAsLong=1000
buffersizeandgrowth
Privatem_nInitialSizeAsLong
Privatem_nGrowthAsLong
bufferandbuffercounters
Privatem_sTextAsString
Privatem_nSizeAsLong
Privatem_nPosAsLong
PrivateSubClass_Initialize()
'
setdefaultsforsizeandgrowth
m_nInitialSize=DEF_INITIALSIZE
m_nGrowth=DEF_GROWTH
initializebuffer
InitBuffer
EndSub
settheinitialsizeandgrowthamount
PublicSubInit(ByValInitialSizeAsLong,ByValGrowthAsLong)
IfInitialSize>
0Thenm_nInitialSize=InitialSize
IfGrowth>
0Thenm_nGrowth=Growth
initializethebuffer
PrivateSubInitBuffer()
m_nSize=-1
m_nPos=1
growthebuffer
PrivateSubGrow(OptionalMinimimGrowthAsLong)
initializebufferifnecessary
Ifm_nSize=-1Then
m_nSize=m_nInitialSize
m_sText=Space$(m_nInitialSize)
Else
justgrow
DimnGrowthAsLong
nGrowth=IIf(m_nGrowth>
MinimimGrowth,
m_nGrowth,MinimimGrowth)
m_nSize=m_nSize+nGrowth
m_sText=m_sText&
Space$(nGrowth)
EndIf
trimthebuffertothecurrentlyusedsize
PrivateSubShrink()
Ifm_nSize>
m_nPosThen
m_nSize=m_nPos-1
m_sText=RTrim$(m_sText)
addasingletextstring
PrivateSubAppendInternal(ByValTextAsString)
If(m_nPos+Len(Text))>
m_nSizeThenGrowLen(Text)
Mid$(m_sText,m_nPos,Len(Text))=Text
m_nPos=m_nPos+Len(Text)
addanumberoftextstrings
PublicSubAppend(ParamArrayText())
DimnArgAsLong
FornArg=0ToUBound