Home
Map
String.Equals FunctionUse String.Equals to test two strings for equality. Examine string.ReferenceEquals.
VB.NET
This page was last reviewed on Sep 25, 2022.
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.
Function
Some examples. 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.
Shared
Info The 2 strings a1 and a2 are equal in character contents so all methods evaluate to True except the ReferenceEquals function.
Detail This method doesn't care about the contents of the String, just its memory location.
And In this example, the 2 variables (a1 and a1) point to different memory locations.
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 Module
1 2 3 5
Operator. 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.
Note We see that the "=" operator compiles to a 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
Optimization. Are there any good ways to make String.Equals faster? In my experience, trying to rewrite String.Equals with loops yields a slower method.
Tip One of the best optimizations you can make is to change your program to use shorter Strings.
Tip 2 Another optimization requires that you change your program so the differences in the Strings come near the start.
Summary. We examined the String.Equals function, and all the different syntax forms with which you can invoke it, in the VB.NET language.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Sep 25, 2022 (edit).
Home
Changes
© 2007-2024 Sam Allen.