Question

Trivial I know, but just interested

I've got a stringbuilder variable, that I want to return the contents of, but if it's empty I want to return "|", so is it best to use stringbuilder.tostring in the compare statement e.g

   If lReturnStringBuilder.ToString = String.Empty Then
                lReturnStringBuilder.Append("|")
            End If
return lreturnStringBuilder.tostring

or is it best to convert it to a string, and compare that, even though that means loading up a new variable and the allocating string space for that e.g

Dim lString as string = lReturnStringBuilder.ToString
if lString = string.empty then
      lstring = "|"
end if
return lString
Was it helpful?

Solution

This is the sort of micro-optimisation that you really just don't need to worry about. However, I will post what I would think is most elegant (and efficient) way of doing this anyway:

Dim result = If(lReturnString.Length = 0, "|", lReturnString.ToString())

This saves converting an empty StringBuilder to a string unnecessarily (or then calling Append, which is definitely not required). Note the use of the inline If statement (VB 9.0), which does not evaluate both statements in any one case, as it is a language construct and not a function (exactly equivalent to a normal If statement with variable assignments).

OTHER TIPS

You are allocating the "string space" regardless of what you do. The ToString function gives you a string, whether you assign the value to a variable or not. So I would suggest that you would be best off assigning the value of ToString() to a variable and then testing that variable value for an empty string. Something like (sorry, I'm a C# guy, but hopefully this will work in VB):

Dim returnVal as String
returnVal = lReturnString.ToString()
If String.IsNullOrEmpty(returnVal) Then
  returnVal = "|"
End If

You should avoid calling ToString on the StringBuilder and then append more to it. When you call the ToString method, you get the string that was used internally by the StringBuilder. If you then append more to the StringBuilder, it has to allocate a new string.

Just use the Length property to check if the StringBuilder is empty, and if it is you don't have to involve the StringBuilder to create the result.

If lReturnStringBuilder.Length = 0 Then
   Return "|"
Else
   Return lReturnStringBuilder.ToString()
End If

You could use the Length property of your StringBuilder object. This way you can avoid calling ToString() the first time:

If lReturnStringBuilder.Length = 0 Then
   lReturnStringBuilder.Append("|")
End If

Return lReturnStringBuilder.ToString()

or

If lReturnStringBuilder.Length = 0 Then
   Return "|"
End If

Return lReturnStringBuilder.ToString()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top