计算机科学与技术 外文翻译 外文文献 英文文献 提高字符串处理性能的应用程序.docx
- 文档编号:14481805
- 上传时间:2023-04-23
- 格式:DOCX
- 页数:28
- 大小:49.13KB
计算机科学与技术 外文翻译 外文文献 英文文献 提高字符串处理性能的应用程序.docx
《计算机科学与技术 外文翻译 外文文献 英文文献 提高字符串处理性能的应用程序.docx》由会员分享,可在线阅读,更多相关《计算机科学与技术 外文翻译 外文文献 英文文献 提高字符串处理性能的应用程序.docx(28页珍藏版)》请在冰豆网上搜索。
计算机科学与技术外文翻译外文文献英文文献提高字符串处理性能的应用程序
1.所译外文资料:
ImprovingStringHandlingPerformanceinASPApplications
①作者:
JamesMusson
②书名(或论文题目):
③出版社(或刊物名称):
DeveloperServices,MicrosoftUK
④出版时间(或刊号):
March2003
外文资料原文
摘自:
ImprovingStringHandlingPerformanceinASPApplications
JamesMusson
DeveloperServices,MicrosoftUK
March2003
Summary:
MostActiveServerPages(ASP)applicationsrelyonstringconcatenationtobuildHTML-formatteddatathatisthenpresentedtousers.ThisarticlecontainsacomparisonofseveralwaystocreatethisHTMLdatastream,someofwhichprovidebetterperformancethanothersforagivensituation.AreasonableknowledgeofASPandVisualBasicprogrammingisassumed.(11printedpages)
Contents
Introduction
ASPDesign
StringConcatenation
TheQuickandEasySolution
TheStringBuilder
TheBuilt-inMethod
Testing
Results
Conclusion
Introduction
WhenwritingASPpages,thedeveloperisreallyjustcreatingastreamofformattedtextthatiswrittentotheWebclientviatheResponseobjectprovidedbyASP.YoucanbuildthistextstreaminseveraldifferentwaysandthemethodyouchoosecanhavealargeimpactonboththeperformanceandthescalabilityoftheWebapplication.OnnumerousoccasionsinwhichIhavehelpedcustomerswithperformance-tuningtheirWebapplications,IhavefoundthatoneofthemajorwinshascomefromchangingthewaythattheHTMLstreamiscreated.InthisarticleIwillshowafewofthecommontechniquesandtestwhateffecttheyhaveontheperformanceofasimpleASPpage.
ASPDesign
ManyASPdevelopershavefollowedgoodsoftwareengineeringprinciplesandmodularizedtheircodewhereverpossible.Thisdesignnormallytakestheformofanumberofincludefilesthatcontainfunctionsmodelingparticulardiscretesectionsofapage.Thestringoutputsfromthesefunctions,usuallyHTMLtablecode,canthenbeusedinvariouscombinationstobuildacompletepage.SomedevelopershavetakenthisastagefurtherandmovedtheseHTMLfunctionsintoVisualBasicCOMcomponents,hopingtobenefitfromtheextraperformancethatcompiledcodecanoffer.
Althoughthisiscertainlyagooddesignpractice,themethodusedtobuildthestringsthatformthesediscreteHTMLcodecomponentscanhavealargebearingonhowwelltheWebsiteperformsandscales—regardlessofwhethertheactualoperationisperformedfromwithinanASPincludefileoraVisualBasicCOMcomponent.
StringConcatenation
ConsiderthefollowingcodefragmenttakenfromafunctioncalledWriteHTML.TheparameternamedDataissimplyanarrayofstringscontainingsomedatathatneedstobeformattedintoatablestructure(datareturnedfromadatabase,forinstance).
CopyCode
FunctionWriteHTML(Data)
DimnRep
FornRep=0to99
sHTML=sHTML&vbcrlf_
&"
&Data(0,nRep)&"
&Data(1,nRep)&"
&Data(2,nRep)&"
&Data(3,nRep)&"
&Data(4,nRep)&"
&Data(5,nRep)&"
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.
TheQuickandEasySolution
Therearetwowaystomitigatetheeffectofstringconcatenations,thefirstistotryanddecreasethesizeofthestringsbeingmanipulatedandthesecondistotryandreducethenumberofstringallocationoperationsbeingperformed.LookattherevisedversionoftheWriteHTMLcodeshownbelow.
CopyCode
FunctionWriteHTML(Data)
DimnRep
FornRep=0to99
sHTML=sHTML&(vbcrlf_
&"
&Data(0,nRep)&"
&Data(1,nRep)&"
&Data(2,nRep)&"
&Data(3,nRep)&"
&Data(4,nRep)&"
&Data(5,nRep)&"
Next
WriteHTML=sHTML
EndFunction
Atfirstglanceitmaybedifficulttospotthedifferencebetweenthispieceofcodeandtheprevioussample.ThisonesimplyhastheadditionofparenthesesaroundeverythingaftersHTML=sHTML&.Thisactuallyreducesthesizeofstringsbeingmanipulatedinmostofthestringconcatenationoperationsbychangingtheorderofprecedence.IntheoriginalcodesampletheASPcomplierwilllookattheexpressiontotherightoftheequalssignandjustevaluateitfromlefttoright.Thisresultsin16concatenationoperationsperiterationinvolvingsHTMLwhichisgrowingallthetime.Inthenewversionwearegivingthecompilerahintbychangingtheorderinwhichitshouldcarryouttheoperations.Nowitwillevaluatetheexpressionfromlefttorightbutalsoinsideout,i.e.insidetheparenthesesfirst.Thistechniqueresultsin15concatenationoperationsperiterationinvolvingsmallerstringswhicharenotgrowingandonlyonewiththelarge,andgrowing,sHTML.Figure1showsanimpressionofthememoryusagepatternsofthisoptimizationagainstthestandardconcatenationmethod.
Figure1 Comparisonofmemoryusagepatternbetweenstandardandparenthesizedconcatenation
Usingparenthesescanmakequiteamarkeddifferenceinperformanceandscalabilityincertaincircumstances,asIwilldemonstratelaterinthisarticle.
TheStringBuilder
Wehaveseenthequickandeasysolutiontothestringconcatenationproblem,andformanysituationsthismayprovidethebesttrade-offbetweenperformanceandefforttoimplement.Ifwewanttogetseriousaboutimprovingtheperformanceofbuildinglargestrings,however,thenweneedtotakethesecondalternative,whichistocutdownthenumberofstringallocationoperations.InordertoachievethisaStringBuilderisrequired.Thisisaclassthatmaintainsaconfigurablestringbufferandmanagesinsertionsofnewpiecesoftextintothatbuffer,causingstringreallocationonlywhenthelengthofthetextexceedsthelengthofthestringbuffer.TheMicrosoft.NETframeworkprovidessuchaclassforfree(System.Text.StringBuilder)thatisrecommendedforallstringconcatenationoperationsinthatenvironment.IntheASPandclassicVisualBasicworldwedonothaveaccesstothisclass,soweneedtobuildourown.BelowisasampleStringBuilderclasscreatedusingVisualBasic6.0(error-handlingcodehasbeenomittedintheinterestofbrevity).
CopyCode
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
EndSub
'initializethebuffer
PrivateSubInitBuffer()
m_nSize=-1
m_nPos=1
EndSub
'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
EndSub
'trimthebuffertothecurrentlyusedsize
PrivateSubShrink()
Ifm_nSize>m_nPosThen
m_nSize=m_nPos-1
m_sText=RTrim$(m_sText)
EndIf
EndSub
'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)
EndSub
'addanumberoftextstrings
PublicSubAppend(ParamArrayText())
DimnArgAsLong
FornArg=0ToUBound
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- 计算机科学与技术 外文翻译 外文文献 英文文献 提高字符串处理性能的应用程序 计算机科学 技术 外文 翻译 文献 英文 提高 字符串 处理 性能 应用程序