Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: VB7
Expertise: Advanced
Jul 27, 2002



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Faster string comparison with the Is operator

.NET strings are objects, so what you store in a String variable is actually a reference to a String object allocated in the managed heap. Even though the VB.NET compiler attempts to hide the object nature of strings as much as it can - for example, you don't need to declare a String object with a New operator - in many cases being aware of their object nature can help you in making the most out of strings, as well as avoid some subtle programming mistakes. For example, consider this code:

Dim s1 As String = "One"
Dim s2 As String = "Two"
Dim res As String 

' Randomly assign Res from s1 or s2
If Rnd < 0.5 Then
    res = s1
    res = s2
End If
' ...
' ...
' later we test the Res variable
If res = s1 Then
    ' Res is equal to s1
    ' Res is equal to s2
End If
The above code is the kind of code that a VB6 developer would write, but it can be improved remarkably by recognizing that strings are objects. In fact, the Res variable contains either a reference to the same object pointed to by the s1 variable or the object pointed to by the s2 variable, so you can make the test faster by using the Is operator:

If res Is s1 Then
    ' Res is equal to s1
    ' Res is equal to s2
End If
Because the VB.NET compiler creates a single string object for all the string constants that have the same value, the same kind of optimization can be applied when constant strings are involved. Consider this code:

Dim color As String
' get a random color value, in the range 0 to 2
Select Case New Random().Next(0, 2)
    Case 0 : color = "Black"
    Case 1 : color = "White"
    Case Else : color = "Unknown"
End Select
' ...
' ...
' later we test the color
If color Is "Black" Then       ' instead of the = operator
    ' color is black
ElseIf color Is "White" Then   ' instead of the = operator
    ' color is white
    ' color is unknown
End If
Francesco Balena
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date