Search
Close this search box.

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 = operator17,1143025 sec.
Using the Equals() function15,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

This article is part of the GWB Archives. Original Author: Viktor Bergman

Related Posts