这些情况使用StringBuilder代替String(抄袭加翻译)

本文探讨了String与StringBuilder在.NET中的不同之处,包括它们的可变性、内存分配方式及应用场景等。介绍了如何根据不同的需求选择合适的类型以提高程序效率。

String和StringBuilder的不同:

It belongs to String namespace

It belongs to String. Text namespace

String object is immutable

StringBuilder object is mutable

Assigning:

String s= "something important";

Assigning:

StringBuilder sbuild= new StringBuilder("something important");

We can use '+' operator or Concat method to concatenate the strings.

Here we are using Append method.

When string concatenation happens, additional memory will be allocated.

Here additional memory will be allocated when the string buffer capacity exceeds only.

 

对于时间关键的程序在以下情况使用StringBuilder代替String:

  • If the number of appends is unknown. (要连接的字符串数量不知道)
  • If appending is on string variables instead of string literals. (连接的是String对象而不是字符串)
  • If string concatenation is in loops. (字符串的连接在循环中)
  • Concatenating string objects returned by multiple methods.(连接被多个方法返回的String对象)

(from :http://www.c-sharpcorner.com/UploadFile/satisharveti/codeperpart108252009063227AM/codeperpart1.aspx)

(from: http://www.c-sharpcorner.com/UploadFile/jitendra1987/4169/)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值