devxlogo

Faster string comparison with the Is operator

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 s2If Rnd < 0.5 Then    res = s1Else    res = s2End If' ...' ...' later we test the Res variableIf res = s1 Then    ' Res is equal to s1Else     ' Res is equal to s2End 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 s1Else     ' Res is equal to s2End 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 2Select Case New Random().Next(0, 2)    Case 0 : color = "Black"    Case 1 : color = "White"    Case Else : color = "Unknown"End Select' ...' ...' later we test the colorIf color Is "Black" Then       ' instead of the = operator    ' color is blackElseIf color Is "White" Then   ' instead of the = operator    ' color is whiteElse    ' color is unknownEnd If

See also  Why ChatGPT Is So Important Today
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist