Can you optimize this code ? (Is GoTo evil ?)
Posted
Monday, June 06, 2005 11:01 AM
by
bill
yesterday I posted a bit of code that was checkign to see if a string was whitespace only. Let's assume the assumption I made was correct, that checkign the middle of the string then spreading out in each direction is the best way of doing that.
So the code I worte yesterday had some branching "issues". As I wrote it, I really felt I was missing something obvious... you know that, "this just doesn't feel right" kind of feeling. To do the branching I used a boolean flag, hasNonWhitespace. The only alternative I could think of was to use a GoTo statement. So here's the first cut, and also a second version using GoTo. Is GoTo evil ? Can you optimize this code some other way ????
Public Function IsWhitespaceOnly(ByVal stringToCheck As String, ByVal ParamArray whitespaceChars() As Char) As Boolean
Dim length As Int32 = stringToCheck.Length
Dim middle As Int32 = length \ 2
Dim first As Int32 = middle
Dim second As Int32 = middle + 1
Dim chr As Char
If whitespaceChars Is Nothing OrElse whitespaceChars.Length = 0 Then
whitespaceChars = New Char() {" "c, ChrW(&H3000)}
End If
Dim whitespaceUbound As Int32 = whitespaceChars.Length - 1
Dim hasNonWhitespace As Boolean = False
For i As Int32 = 0 To middle
If first >= 0 Then
hasNonWhitespace = True
chr = stringToCheck.Chars(first)
For j As Int32 = 0 To whitespaceUbound
If chr = whitespaceChars(j) Then
hasNonWhitespace = False
Exit For
End If
Next
first -= 1
End If
If hasNonWhitespace Then Return False
If second < length Then
hasNonWhitespace = True
chr = stringToCheck.Chars(second)
For j As Int32 = 0 To whitespaceUbound
If chr = whitespaceChars(j) Then
hasNonWhitespace = False
Exit For
End If
Next
second += 1
End If
If hasNonWhitespace Then Return False
Next
Return Not hasNonWhitespace
End Function
' using GoTo
Public Function IsWhitespaceOnly(ByVal stringToCheck As String, ByVal ParamArray whitespaceChars() As Char) As Boolean
Dim length As Int32 = stringToCheck.Length
Dim middle As Int32 = length \ 2
Dim first As Int32 = middle
Dim second As Int32 = middle + 1
Dim chr As Char
If whitespaceChars Is Nothing OrElse whitespaceChars.Length = 0 Then
whitespaceChars = New Char() {" "c, ChrW(&H3000)}
End If
Dim whitespaceUbound As Int32 = whitespaceChars.Length - 1
For i As Int32 = 0 To middle
If first >= 0 Then
chr = stringToCheck.Chars(first)
For j As Int32 = 0 To whitespaceUbound
If chr = whitespaceChars(j) Then
first -= 1
GoTo secondpart
End If
Next
Return False
End If
secondpart:
If second < length Then
chr = stringToCheck.Chars(second)
For j As Int32 = 0 To whitespaceUbound
If chr = whitespaceChars(j) Then
second += 1
GoTo nextpart
End If
Next
Return False
End If
nextpart:
Next
Return True
End Function