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:

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:

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和String进行字符串操作的时间复杂性和空间复杂性,展示了在频繁修改字符串内容时使用StringBuilder能显著提高效率。

被折叠的 条评论
为什么被折叠?



