Why I use Equals() and Comparative Simplicity
Students frequently ask me why I prefer Equals() over = when coding VB equality comparisons. To answer this question, we need to get into ILDasm, the tool that we can use to view IL code in any .Net assembly.
Take the following VB snippet:
public sub doStuff()
dim a as String = "Cats"
dim b as String = "Dogs"
if a = b then
MessageBox.Show( "Unlikely!" )
end if
if a.Equals( b ) then
MessageBox.Show( "Still unlikely!" )
end if
end sub
Compile your program and check out the IL this generates using ILDasm. We can use ILDasm by firing up ILDasm.exe and manually browsing to the assembly with our doStuff() method in it; ILDasm.exe can be found in your \Program Files\Microsoft Visual Studio .NET\FrameworkSDK\Bin directory. Alternately, and this is my preferred approach, I add ILDasm as a VS.Net add-in (by going to Tools-->External Tools and choosing to “Add” a new Tool with the path to ILDasm.exe as the “Command” (it's C:\Program Files\Microsoft Visual Studio .NET\FrameworkSDK\Bin\ildasm.exe on my machine) and the “Argument“ $(TargetPath) -- this fires up ILDasm for the assembly I'm working with in VS.Net, very slick!). Note, you only have to add ILDasm once to your External Tools; from then on, it can be invoked from the Tools menu directly.
Regardless of how you do it, open ILDasm and explore the treeview representation of your assembly (for more on ILDasm, check out this article or this MSDN piece). Expand some of the ILDasm nodes and appreciate the hierarchical view ILDasm provides . . . by double clicking on a method in your class, you can peruse the IL.
If you open the doStuff method in ILDasm you'll see the instructions created by using “=“ versus Equals(). The “=“ approach creates a call like the following:
IL_0010: call int32 [Microsoft.VisualBasic]Microsoft.VisualBasic.CompilerServices.StringType::StrCmp(string,
string,
bool)
while the Equals() approach creates the following:
IL_0026: callvirt instance bool [mscorlib]System.String::Equals(string)
The approach using mscorlib, Equals(), is smaller and quicker than the = method in VB because with “=” we're calling into the VB specific string comparison logic instead of the leaner .Net framework implementation. Can a human appreciate the performance difference for a single comparison, certainly not, but in looping situations and other performance critical operations, it's good to avoid the “=” comparison. I use “Equals()” instead of “=” all the time so I'm in the habit of producing the most efficient code as possible.
Note that the c# “==” comparison operator doesn't suffer from the same legacy comparison framework; if( a==b ) creates the same IL as if( a.Equals( b ) ) in c#. Score another point for c#. Since I do a lot of programming in both languages, anything I can do to cut down on language nuances is a plus, so I stick with Equals() when using c# too; it makes my life comparatively simpler!
Happy .Netting!