VB Quark #5: C is for Char

Can you pick the problem with this code ? :

      Dim currentChar As Char

      For i = 0 To
largenumber
         currentChar = getChar(i)
        
If currentChar = "a" Then
            count += 1
        
End If
     
Next

 

The answer of course is the literal “a” is of type string, not of type Char. Hence currentChar gets implicitly widened to a String to make the expression a string comparison expression. This means a new string is created with the contents of currentChar on each iteration, and the comparison is a string comparison which checks for null strings and empty strings and then does a compare ordinal etc. This is incredibly inefficient.

If “a” was typed as Char, then the comparison is a simple low level IL compare of the underlying values (int16’s).

You can use CChar, as in CChar(“a”), but it’s a lot easier just to add the type literal suffix c, eg “a”c

      Dim currentChar As Char

      For i = 0 To
largenumber
         currentChar = getChar(i)
        
If currentChar = "a"c Then
            count += 1
        
End If
     
Next

The change in this code is about 20 fold performance improvement (run as release build outside of Visual Studio). That’s a 20 fold increase just by typing one extra letter !!

This example was based on real sample code where a massive file was being parsed char by char.  There too, attention to the fine detail showed a massive performance improvement over the original code. It’s often the little things that can make a huge difference.

 

This VB quark was brought to you by the type literal “c”

This entry was posted in 13569, 16311, 491, 5162, 5726, 7341. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>