This piece of information examines the performance of result when using Equals as against "=" operator.
I was thinking about why one should use
Equals in VB.NET instead of
“=” operator as we used to do in VB 6.0.
The following two versions of the code examines the performance of comparing two strings using
'=' operator and
Equals .
In the following test cases, I have recorded the time before starting loop and after the loop ends. At the end I am printing out the difference of the time, as it is the time taken to execute the code 99999 times.
1. Using = operator for comparison:
Sub Main()
Dim startTime As DateTime
Dim endTime As DateTime
'' Take two Test Strings
Dim strTestSubject1 As String = "Krishna is gooood...."
Dim strTestSubject2 As String = "Krishna is baaaaad..."
Dim i As Integer = 0
startTime = DateTime.Now
While i < 99999
If strTestSubject1 = strTestSubject2 Then
' Do Nothing
End If
Console.WriteLine(i)
i = i + 1
End While
endTime = DateTime.Now
Console.WriteLine(vbCrLf & endTime.Subtract(startTime).TotalSeconds)
Console.ReadKey()
End Sub
The time taken to execute the above code is 13.67205 seconds
Sub Main()
Dim startTime As DateTime
Dim endTime As DateTime
'' Take two Test Strings
Dim strTestSubject1 As String = "Krishna is gooood...."
Dim strTestSubject2 As String = "Krishna is baaaaad..."
Dim i As Integer = 0
startTime = DateTime.Now
While i < 99999
If strTestSubject1.Equals(strTestSubject2) Then
' Do Nothing
End If
Console.WriteLine(i)
i = i + 1
End While
endTime = DateTime.Now
Console.WriteLine(vbCrLf & endTime.Subtract(startTime).TotalSeconds)
Console.ReadKey()
End Sub
The time taken to execute the above code is 13.5782988 seconds
When I took the two different test strings the Results are as under:
strTestSubject1 = ".net is gooood...."
strTestSubject2 = ".net is baaaaad..."
13.9533036 seconds When I used = operator
13.6095492 seconds When I used Equals
From the above observations, it is clear that
using Equals is much more faster than using = operator for strings comparison resulting in better performance througput..
Thanks one and All.