performance while doing string concatenation - algorithm string strings c# -


i using following code append strings

string res = string.empty; int ite = 100000; for(int i= 0; < ite; i++) {     res += "5"; } 

it taking lot of time, later changed code

string res = string.empty; int ite = 100000; res = getstr(ite / 2) + getstr(ite - (ite / 2));   //body of getstr method private static string getstr(int p) {     if (p == 1)         return "5";     else if (p == 0)         return string.empty;     string r1 = getstr(p / 2); //recursive     string r2 = getstr(p - (p / 2)); //recursive       return (r1 + r2); } 

which in opinion nothing number of times strings concatenated approximately same in previous approach.

but using approach there significant improvement in performance code taking around 2500 ms (on machine) taking 10 ms.

i ran profiler on cpu time , couldn't arrive @ understanding why there improvement in performance. can please explain this.

note: intentionally not using stringbuilder, in order understand above.

you need think why string concatenation slow. strings immutable, when do:

somestring+= "5"; 

you have copy entire contents of somestring , string 1 larger , copy in 5 part. if think it, gets slower , slower longer string gets.

with recursive function doing divide , conquer strategy minimize number of big string concatenations need. example, if had length of 8, in first case you'd doing:

"5" + "5"  "55" + "5" "555" + "5" "5555" + "5" "55555" + "5" "555555" + "5" "5555555" + "5"    // 7 total concatenations 

in recursive model doing:

"5" + "5"         // 4 times "55" + "55"       // twice "5555" + "5555"   // once  

so doing less big concatenations.

and, of course, assume op knows comment, else; if need concatenate non-trivial number of strings, use stringbuilder optimized building strings appending them together.


Comments

Popular posts from this blog

javascript - Karma not able to start PhantomJS on Windows - Error: spawn UNKNOWN -

Nuget pack csproj using nuspec -

c# - Display ASPX Popup control in RowDeleteing Event (ASPX Gridview) -