Section17.1:WhataStringBuilderisandwhentouseone
AStringBuilderrepresentsaseriesofcharacters,whichunlikeanormalstring,aremutable.Oftentimesthereisa needtomodifystringsthatwe’vealreadymade,butthestandardstringobjectisnotmutable.Thismeansthateach timeastringismodified,anewstringobjectneedstobecreated,copiedto,andthenreassigned.
stringmyString=”Apples”;
mystring+=”aremyfavoritefruit”;
Intheaboveexample,myStringinitiallyonlyhasthevalue”Apples”.However,whenweconcatenate`”aremy favoritefruit”‘,whatthestringclassdoesinternallyneedstodoinvolves:
- CreatinganewarrayofcharactersequaltothelengthofmyStringandthenewstringweareappending.
- CopyingallofthecharactersofmyStringintothebeginningofournewarrayandcopyingthenewstringinto the end of the array.
- CreateanewstringobjectinmemoryandreassignittomyString.
For a single concatenation, this is relatively trivial. However, what if needed to perform many append operations, say, in a loop?
StringmyString=””;
for(inti=0;i<10000;i++)
myString+=””;//puts10,000spacesintoourstring
Duetotherepeatedcopyingandobjectcreation,thiswillbringsignificantlydegradetheperformanceofour program. We can avoid this by instead using a StringBuilder.
StringBuildermyStringBuilder=newStringBuilder();
for(inti=0;i<10000;i++)
myStringBuilder.Append(”);
Nowwhenthesameloopisrun,theperformanceandspeedoftheexecutiontimeoftheprogramwillbe significantlyfasterthanusinganormalstring.TomaketheStringBuilderbackintoanormalstring,wecansimply call the ToString()method of StringBuilder.
However,thisisn’ttheonlyoptimizationStringBuilderhas.Inordertofurtheroptimizefunctions,wecantake advantageofotherpropertiesthathelpimproveperformance.
StringBuildersb=newStringBuilder(10000);//initializesthecapacityto10000
IfweknowinadvancehowlongourStringBuilderneedstobe,wecanspecifyitssizeaheadoftime,whichwill preventitfromneedingtoresizethecharacterarrayithasinternally.
sb.Append(‘k’,2000);
ThoughusingStringBuilderforappendingismuchfasterthanastring,itcanrunevenfasterifyouonlyneedto addasinglecharactermanytimes.
Onceyouhavecompletedbuildingyourstring,youmayusetheToString()methodontheStringBuilderto convert it to a basic string. This is often necessary because the StringBuilderclass does not inherit from string.
Forexample,hereishowyoucanuseaStringBuildertocreateastring:
stringRepeatCharacterTimes(charcharacter,inttimes)
{
StringBuilderbuilder=newStringBuilder(“”);for(intcou
nter=0;counter<times;counter++)
{
//AppendoneinstanceofthecharactertotheStringBuilder.
builder.Append(character);
}
//Converttheresulttostringandreturnit.
returnbuilder.ToString();
}
Inconclusion,StringBuildershouldbeusedinplaceofstringwhenmanymodificationstoastringneedtobe madewithperformanceinmind.
Section17.2:UseStringBuildertocreatestringfromalarge number of records
publicstringGetCustomerNamesCsv()
{
List<CustomerData>customerDataRecords=GetCustomerData();//Returnsalargenumberof records,say,10000+
StringBuildercustomerNamesCsv=newStringBuilder(); foreach(CustomerDatarecordincustomerDataRecords)
{
customerNamesCsv
.Append(record.LastName)
.Append(‘,’)
.Append(record.FirstName)
.Append(Environment.NewLine);
}
returncustomerNamesCsv.ToString();
}
About us and this blog
We are a digital marketing company with a focus on helping our customers achieve great results across several key areas.
Request a free quote
We offer professional SEO services that help websites increase their organic search score drastically in order to compete for the highest rankings even when it comes to highly competitive keywords.
Subscribe to our newsletter!
More from our blog
See all postsRecent Posts
- Chapter120:YieldKeyword 20/05/2024
- Chapter119:LockStatement 19/05/2024
- Chapter118:Makingavariablethreadsafe 18/05/2024