string v.s. stringbuilder

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi,

Can anyone please explain to me what the advantages in using String data
type over StringBuilder data type and vice versa? Is that true that it's
better to use StringBuilder "Append()" to concat strings than using "+"?
Which one is faster? Efficient?

Thanks,
-P
 
when you write

string s = s1 + s2;
a StringBuilder is silently created for you to create a new string and
whatever way you write it it's the same.

when you write
string s = s1 + s2;
s += s3;
s += s4;

3 StringBuilder are silently created for you (one for each line), so it's
better to do it explicitely....

caution: this is mostly guessing as I didn't looked at the disasembly
code...
 
Strings are immutable. That is that once a string object is created in
memory, the data in that memory address can't be changed. So, if you have a
string and then modify it, say like this:

Dim x as String = "Test"
x +="ing"

a second string object will be created in memory and the object variable (x)
will now point to the new string, leaving the old string object in memory,
waiting to be collected at some later time.

If you use a StringBuilder like this:

Dim x as New System.Text.StringBuilder("Test")
x.Append("ing")

only one StringBuilder is created in memory.

In cases where you will be doing heavy manipulation of a string, you will
find that using a StringBuilder will be more efficient.

Try this....Create a Webform with 2 buttons (btnString and btnSB) and a
label next to each (lblString and lblSB). Then add this code to the click
events of the buttons:


Private Sub btnString_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnString.Click
'Change a String 7500 times and see how long it takes to do it
Dim theString As String = "A very long string."
Dim i As Integer
Dim endTime As DateTime
Dim startTime As DateTime = Now
For i = 1 To 7500
theString += "Even more stuff added."
Next
endTime = Now
lblString.Text = endTime.Subtract(startTime).ToString
End Sub

Private Sub btnSB_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnSB.Click
'Change a StringBuilder 7500 times and see how long it takes to do
it
Dim theString As New System.Text.StringBuilder("A very long
string.")
Dim i As Integer
Dim endTime As DateTime
Dim startTime As DateTime = Now
For i = 1 To 7500
theString.Append("Even more stuff added.")
Next
endTime = Now
lblSB.Text = endTime.Subtract(startTime).ToString
End Sub

You will see that the StringBuilder is significantly more efficient than
using a string.
 
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."

So, to answer the question, at what point is it more efficient, I wrote a
little tester. The StringBuilder returned Sub-10ms times (DateTime not
capable of registering < 10ms) at 1000 or fewer iterations of a loop simply
appending the string "string". The += method of concatenation takes 15+ms for
the same iterations. At 5000 iterations, the += method was becoming much
slower at 218ms. versus the StringBuilder which was still sub 10ms.Even at
10000 iterations, the SB was sub 10, while the concat method had gone over
1.2 seconds. My test code is as follows:


private void UpdateTime()

{

int iterations = Int32.Parse(txtIterations.Text);

string theString = txtTheString.Text;

DateTime strCall = DateTime.Now;

string targetString = null;

for(int x = 0 ; x < iterations ; x++)

{

targetString += theString;

}

TimeSpan time = (DateTime.Now - strCall);

txtConcatTime.Text = time.TotalMilliseconds.ToString();

//StringBuilder

DateTime inCall = DateTime.Now;

StringBuilder sb = new StringBuilder(theString);

for(int x = 0 ; x < iterations ; x++)

{

sb.Append(theString);

}

time = (DateTime.Now - inCall);

txtStringBTime.Text = time.TotalMilliseconds.ToString();

MessageBox.Show("done");

}

HTH
Sudhakar Sadasivuni
http://one.mvpblog.com
 
Lloyd Dupont said:
string s = s1 + s2;
a StringBuilder is silently created for you to create a new string and
whatever way you write it it's the same.

No it's not. String.Concat(s1, s2) is called - that's marginally more
efficient than using StringBuilder, because the length can be
calculated first.
when you write
string s = s1 + s2;
s += s3;
s += s4;

3 StringBuilder are silently created for you (one for each line), so it's
better to do it explicitely....

No StringBuilders are created, but a separate string is created each
time.

Now, the above code is probably quicker than using StringBuilder
(marginally) but when you get beyond just a few concatenations,
StringBuilder becomes more efficient - potentially *much* more
efficient. This is very important when you're building up a string in a
loop, and you don't know at compile time how many iterations of the
loop there will be.
 
learning something tonight!
unlike java, hey!

Jon Skeet said:
No it's not. String.Concat(s1, s2) is called - that's marginally more
efficient than using StringBuilder, because the length can be
calculated first.


No StringBuilders are created, but a separate string is created each
time.

Now, the above code is probably quicker than using StringBuilder
(marginally) but when you get beyond just a few concatenations,
StringBuilder becomes more efficient - potentially *much* more
efficient. This is very important when you're building up a string in a
loop, and you don't know at compile time how many iterations of the
loop there will be.
 
I agree with Jon. use String if you only have to concatenate a few times but
string builder for larger concatenates .
Lloyd Dupont said:
learning something tonight!
unlike java, hey!
 
no, why would it? Are you thinking the expense is because of the
stringbuilder allocation?

Yup, along with some thread synchronization. I seem to remember the
range of 5-10 being the "normal" area where the two are roughly equal,
and after that StringBuilder will perform better.

Of course, it depends on the lengths of the strings being appended - if
every call to Append ends up creating a new string inside
StringBuilder, due to its length, then that will presumably still be
slower than using String.Concat.
 
Wow, what a pile of contracticting information.

Using strings directly for concactenation is more efficient for small
appends that don't happen often. If you are doing anything like that inside
a loop or a recursion, or if you are a string builder is better because of
the way memory is managed. That's the general rule of thumbs, but if you
look on the internet you should be able to find longer discussion on the
topic and even benchmarks.

Etienne Boucher.
 
Now, the above code is probably quicker than using StringBuilder
(marginally)
no, why would it? Are you thinking the expense is because of the
stringbuilder allocation?
 
Back
Top