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…

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

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

New on Geeks with Blogs

  • We Won The One Award I Actually Care About

    Full Scale made the Inc. 5000 for the fifth year straight, the 12th listing across my three companies. Here is why the one award you cannot buy is worth stopping for.

  • Your Customers Build the Features Now

    I let a tool I liked sit dead for a year rather than build the features I wanted. An MCP server meant I never had to, and your customers can do the same to your product.

  • Get the Size of a Directory in Linux the Easy Way

    du -sh for the quick answer, ncdu for the cleanup, df for the disk itself: every command for checking directory size in Linux, plus why du and df never agree.

  • Vim Search and Replace: The Ultimate Guide

    One :%s command replaces every match in a file before a find dialog would even open. The Vim substitute patterns worth the muscle memory: flags, ranges, capture groups, and multi-file edits.