String.Equals
How can you compare 2 strings for equality? With the VB.NET String.Equals
Function in its various syntax forms, including the equals operator, you can do this.
We look at examples of string
equality testing. We try to understand the concept of String
references and the ReferenceEquals
function.
This program first creates 2 String
variables. Next, we show the instance Equals
method, the Shared Equals
method, the equals operator, and ReferenceEquals
and Compare.
ReferenceEquals
function.String
, just its memory location.Module Module1 Sub Main() Dim a1 As String = "a" + 1.ToString() Dim a2 As String = "a" + 1.ToString() If a1.Equals(a2) Then Console.WriteLine(1) End If If String.Equals(a1, a2) Then Console.WriteLine(2) End If If a1 = a2 Then Console.WriteLine(3) End If If String.ReferenceEquals(a1, a2) Then Console.WriteLine(4) End If If String.Compare(a1, a2) = 0 Then Console.WriteLine(5) End If End Sub End Module1 2 3 5
At first it seems that the equals operator is the simplest and fastest way to compare strings. After all, it is only one character. But let's look at op_Equality
in IL Disassembler.
String.Equals
function call. This will be inlined in Release mode by the JIT compiler..method public hidebysig specialname static bool op_Equality(string a, string b) cil managed { // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call bool System.String::Equals(string, string) IL_0007: ret } // end of method String::op_Equality
Are there any good ways to make String.Equals
faster? In my experience, trying to rewrite String.Equals
with loops yields a slower method.
We examined the String.Equals
function, and all the different syntax forms with which you can invoke it, in the VB.NET language.