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

来源:互联网 发布:10月经济数据点评 编辑:程序博客网 时间:2024/05/29 11:16

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/)

 

原创粉丝点击