2

All,

For the string string s = "abcd", does string w = s.SubString(2) return a new allocated String object i.e. string w = new String ("cd") internally or a String literal?

For StringBuilder, when appending string values and if the size of the StringBuilder needs to be increased, are all the contents copied over to a new memory location or simply the pointers to each of the earlier String value are reassigned to the new location?

5 Answers 5

5

String is immutable, so any operation that "changes" the string, will in effect return a new string. This includes SubString and all other operations on String, including those that does not change the length (such as ToLower() or similar).

StringBuilder contains internally a linked list of chunks of characters. When it needs to grow, a new chunk is allocated and inserted at the end of the list, and data is copied here. In other words, the whole StringBuilder buffer will not be copied on an append, only the data you are appending. I double-checked this against the Framework 4 reference sources.

Sign up to request clarification or add additional context in comments.

6 Comments

Thanks for your reply. Actually, my question was more of if String.Substring() returns new String (XXXX) or just "XXXX". Got my answer though
It will always be a new object. In fact (as long as no string constants or interned strings are involved), it makes little sense to talk about a difference between returning "new String(XXXX) or "XXXX".
Can you please guide me to the reference sources you are talking about?
Thanks for the link. But I think it is copying from the original string array to the new one entirely. In String.cs, method GetStringForStringBuilder() which takes the original string and the length required it does wstrcpy(dest, src + startIndex, length); where startIndex is 0. Am I correct ?
GetStringForStringBuilder() is for going from String to StringBuilder. I was talking about the StringBuilder internal resize operation.
|
1

For the string string s = "abcd", does string w = s.SubString(2) return a new allocated String object? Yes

For StringBuilder, when appending string values and if the size of the StringBuilder needs to be increased, are all the contents copied over to a new memory location? Yes

Any change in String small or large results in a new String

2 Comments

Actually, all the existing content is not copied over to a new buffer when more space is needed. (This was checked against Framework 4.0 reference sources).
@driis: MSDN says A StringBuilder object maintains a buffer to accommodate the concatenation of new data. New data is appended to the end of the buffer if room is available; **otherwise, a new, larger buffer is allocated, data from the original buffer is copied to the new buffer, then the new data is appended to the new buffer**. Doesn't this means that all the existing data is copied to new buffer?
0

If you are going to make large numbers of edits to a string it better to do this via StringBuilder.

From MSDN:

You can use the StringBuilder class instead of the String class for operations that make multiple changes to the value of a string. Unlike instances of the String class, StringBuilder objects are mutable; when you concatenate, append, or delete substrings from a string, the operations are performed on a single string.

Comments

0

Strings are immutable objects so every time you had to make changes you create a new instance of that string. The substring method does not change the value of the original string.

Regards.

2 Comments

Thanks for your reply. Actually, my question was more of if String.Substring() returns new String (XXXX) or just "XXXX". Got my answer though
Yes, even with the method SubString have a new object on the heap these are reference types and not divalore types, such as variables, for example structures.
0

Difference between the String and StringBuilder is an important concept which makes the difference when an application has to deal with the editing of a high number of Strings.

String

The String object is a collection of UTF-16 code units represented by a System.Char object which belong to the System namespace. Since the value of this objects are read-only, the entire object String has defined as immutable. The maximum size of a String object in memory is 2 GB, or about 1 billion characters.

Immutable Being immutable means that every time a methods of the System.String is used, a new sting object is created in memory and this cause a new allocation of space for the new object.

Example: By using the string concatenation operator += appears that the value of the string variable named test change. In fact, it create a new String object, which has a different value and address from the original and assign it to the test variable.

string test;
test += "red"; // a new object string is created
test += "coding"; // a new object string is created
test += "planet"; // a new object string is created

StringBuilder

The StringBuilder is a dynamic object which belong to the System.Text namespace and allow to modify the number of characters in the string that it encapsulates, this characteristic is called mutability.

Mutability To be able to append, remove, replace or insert characters, A StringBuilder maintains a buffer to accommodate expansions to the string. If new data is appended to the buffer if room is available; otherwise, a new, larger buffer is allocated, data from the original buffer is copied to the new buffer, and the new data is then appended to the new buffer.

StringBuilder sb = new StringBuilder("");
sb.Append("red");
sb.Append("blue");
sb.Append("green ");
string colors = sb.ToString();

Performances

In order to help you better understand the performance difference between String and StringBuilder, I created the following example:

Stopwatch timer = new Stopwatch();
string str = string.Empty;
timer.Start();
for (int i = 0; i < 10000; i++) {
    str += i.ToString();
}
timer.Stop();
Console.WriteLine("String : {0}", timer.Elapsed);

timer.Restart();

StringBuilder sbr = new StringBuilder(string.Empty);
for (int i = 0; i < 10000; i++) {
    sbr.Append(i.ToString());
}
timer.Stop();
Console.WriteLine("StringBuilder : {0}", timer.Elapsed);

The output is

Output
String : 00:00:00.0706661
StringBuilder : 00:00:00.0012373

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.