Use StringBuilder instead of String as possible as you can.

  If you are care a littile about the time your algorithm cost,you should notice that,you my use StringBuilder instead of string itself if you gonna change the string literals.

  Today,I test them,and the result is so much difference.

  Nomal string operates:

  

1  System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();

2             sw.Start();

3             string noBu = "";

4             for (int i = 0; i < 100000; i ++ ) {

5                 noBu += i;

6             }

7             sw.Stop();

8             MessageBox.Show(sw.Elapsed.ToString());

And the result is show with the screenshot below:

Use StringBuilder instead of String as possible as you can.

Do the same work using StringBuilder instead:

1 System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();

2 sw.Start();

3 StringBuilder bu = new StringBuilder();

4 for (int i = 0; i < 100000; i ++ ) {

5 bu.Append(i);

6 }

7 sw.Stop();

8 MessageBox.Show(sw.Elapsed.ToString());

And shows the result with the screenshot below:

Use StringBuilder instead of String as possible as you can.

 

  Now back to our issue,if we do our job regardless the time costs(thought it is impossible),and just focus on the memory it cost.We will easy to know that,if we do use the normal string,for instance,doing 

1 "a" + "b"

expression, it needs to create a memory for "a" literal and one for "b" literal,and create one for "ab"(the string plus result).

  Whereas,if we use StringBuilder instead,since it is not fixed.

  So it is obvious that the Time Complexity and the Space Complexity between them now.

你可能感兴趣的:(StringBuilder)