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:

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.

转载于:https://www.cnblogs.com/listened/p/3513523.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值