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

posted on 2009-11-01 17:16  lantionzy  阅读(255)  评论(1编辑  收藏  举报