Technology1 min read

CodeSOD: Building a Line

By · Published by Everything Blog

In short

The featured implementation reads an entire file into a single variable and appends a line feed to the text. Instead of directly returning the resulting text, the function wraps the complete string inside a string builder only to convert it back into a string immediately. A simple direct return of the concatenated values would achieve the exact same result far more efficiently.

Key points

  • Using a string builder on an already assembled string yields absolutely no performance ad…: Using a string builder on an already assembled string yields absolutely no performance advantages.
  • The featured implementation exemplifies superstitious programming driven by a blind assum…: The featured implementation exemplifies superstitious programming driven by a blind assumption of efficiency.
  • Basic concatenation alongside a direct return would achieve the identical result without…: Basic concatenation alongside a direct return would achieve the identical result without unnecessary abstraction.

Sources checked by our analysis pipeline: 1

There's an unofficial category of posts here that I call "Somebody told us string builders were more efficient, so we always use string builders, regardless of whether or not that actually makes sense," or STUSBWMESWAUSBROWONTAMS, for short. Probably should workshop that name some.

In any case, Adam sends us a new entry for that collection:

Public Function ReadFromFile(ByVal filename As String) As String

Dim sb As StringBuilder = New StringBuilder()

Dim str As String = String.Empty

Using sr As StreamReader = File.OpenText(filename)

str = sr.ReadToEnd()

sb.Append(str & Constants.vbLf)

End Using

Return sb.ToString()

End Function

This function takes a filename, opens a file, reads the entire contents of the file to a variable. It concatenates a line feed to the end of the string it just read, then appends all of that to a string builder. Finally, we return sb.ToString()

, taking the single string in the string builder, appending nothing to it, and returning the result.

I'd almost, almost forgive the code if it was more like:

str = sr.ReadToEnd()

sb.Append(str)

sb.Append(Constants.vbLf)

You're not actually gaining much from this, but…

Technology