sk8er_boy287 wrote:
However, if you can prove that StringBuilder is better than simple string concatenation, you get an A+.
If you need to build a string in a loop the stringbuilder is FAR more efficient then normal string concatenation. I've run into the problem before and learned the hard way. Actually I learned about it a while back using VB6, but VB6 didn't have a nice StringBuilder so I figured out another way around it. A simple example will show the difference. Do I get an A+? :)
Public Class Form1
Private Sub TestStringConcatenation(ByVal loops As Integer, ByVal myText As String)
Dim s As String = ""
For i As Integer = 0 To loops
s &= myText
Next
End Sub
Private Sub TestStringBuilder(ByVal loops As Integer, ByVal myText As String)
Dim sb As New System.Text.StringBuilder
For i As Integer = 0 To loops
sb.Append(myText)
Next
End Sub
Private Sub Button1\_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Const LOOPS As Integer = 1000
Dim myText As String = New String("A"c, 200)
Dim sw As New Stopwatch
sw.Start()
TestStringConcatenation(LOOPS, myText)
sw.Stop()
Console.WriteLine("Normal string concatenation took {0} ticks", sw.ElapsedTicks)
sw.Reset()
sw.Start()
TestStringBuilder(LOOPS, myText)
sw.Stop()
Console.WriteLine("String builder took {0} ticks", sw.ElapsedTicks)
End Sub
End Class
As for the code the OP posted, what's funny about it is how much extra useless code the person used to return a string. All that was needed was a simple line
Return "Current date and time is " + DateTime.Now.ToString()
As someone already mentioned the original code writer probably learned that is was more efficient to use the stringbuilder if you are going to append text to a string. Unfortunatly they didn't use it correctly and didn't really grasp when it's appropriate to use it. I ran a test to see what method performed best. In this case normal string concatenation seemed to out perform stringbuilder. Here is my code I used to see the performance of each method.
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Const TRIALS As Integer = 1000
Const LOOPS As Integer = 1000