C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Info: The 2 strings a1 and a2 are equal in character contents so all methods evaluate to True except the ReferenceEquals function.
ReferenceEquals: 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.
VB.NET program that uses String.Equals
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
Output
1
2
3
5
Note: We see that the "=" operator compiles to a String.Equals function call. This will be inlined in Release mode by the JIT compiler.
Implementation of op_Equality: IL
.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
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.