The ‘=’ operator vs. Equals() in VB.Net

As I was reading yet another chapter in Code Complete Second Edition by Steve McConnell I started to think about the VB operator '=' versus the C equivalent '=='. Even though im a big VB fan I must say the C style is much better. In VB we use the same operator for two purposes, in one place we use it for ASSIGNING data and in another we use it for COMPARING data.

However, I thought that why not use Equals(obj,1 obj2) instead of '=' for comparisons, if not only for the sake of maintaining a more consequent code. Further down that lane I started to wonder if there might be any pros or cons in regard to performance with the two. I have always that that Equals(obj1, obj2) just wraps a 'obj1 = obj2' statement. Daaah NOT ;-).

Here is my test case:

Dim startTime As DateTime
Dim endTime As DateTime

Dim strTestSubject1 As String = ".net is gooood...
Dim strTestSubject2 As String = ".net is baaaaad..."

Dim i As Integer = 0

startTime = DateTime.Now

While i < 99999
If strTestSubject1 = strTestSubject2 Then
'If strTestSubject1.Equals(strTestSubject2)
'Do nothing
End If
Console.WriteLine(i)
i = i + 1
End While
endTime = DateTime.Now
Console.WriteLine(vbCrLf & endTime.Subtract(startTime).TotalSeconds)

The results were not STUNNING but there is actually a difference:

Using the = operator

17,1143025 sec.

Using the Equals() function

15,473205 sec.


The difference is about 1,6410975 seconds ( a rough estimate by just glancing the numbers ;-) ). It does not
seem like a major difference but using the strTestSubject1.Equals(strTestSubject2) is still 0.9 % faster.

There seems to be a lot of discussion about this:
Nick Schweitzer posts a comparison on the both claiming that '=' uses old VB6 libraries…
Cory Smith rebuttals it in his post saying it does not…

Whatever the reason is, it sure seems like Equals IS faster.

posted @ Monday, March 26, 2007 8:07 AM

Print

Comments on this entry:

# re: The ‘=’ operator vs. Equals() in VB.Net

Left by Brian at 12/19/2008 10:36 PM
Gravatar
"=" tests reference equality. If the two reference the same object, they are equal according to "=". The "equals()" method is an overridable Object method like "toString()" that allows you to test your objects equality in a way that says "do their representative values equal each other?"

Java, c# and the like also implement the equals() method, since ==, like vb, tests reference equality.

Your comment:



 (will not be displayed)


 
 
 
 

Live Comment Preview:

 
«November»
SunMonTueWedThuFriSat
25262728293031
1234567
891011121314
15161718192021
22232425262728
293012345