That something between String and StringBuilder(String和StringBuilder之间的异同)

  First, we take some time to have a look at these words: "The String object is immutable. Every time you use one of the methods in the System.String class, you create a new string object in memory, which requires a new allocation of space for that new object. In situations where you need to perform repeated modifications to a string, the overhead associated with creating a new String object can be costly. The System.Text.StringBuilder class can be used when you want to modify a string without creating a new object. For example, using the StringBuilder class can boost performance when concatenating many strings together in a loop."

  1. Look at this two lines:

String name  =   " Hello " ;
name 
=   " Hello cnblogs " ;

  First we create a new String object 'name', then we give name another value. By saying you cannot change the name object means you cannot change the value in name object internally. Indeed, a new name object is created in memory and the value "Hello cnblogs" is assingned to the newly created space.

  2. StringBuilder object is dynamic object, we can expand its package and add more characters. Of course we can also assign a maximum capcity.

  3. The most common operation with a string is concatenation. The string object can use += method to concatenate two strings. And I have just mentioned the disadvantages. But for StringBuilder object, when using Append method, an insertion is done on the existing string. Operation on StringBuilder object is faster than String operations, as the copy is done in the same location. Usage of StringBuilder is more efficient in case large amounts of string manipulations have to be performed. eg:

StringBuilder sb  =   new  StringBuilder();
sb.Append(
" Hello  " );
sb.Append(
" cnblogs " );

 

Go to my home page for more posts

转载于:https://www.cnblogs.com/lantionzy/archive/2009/11/01/1594000.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值