C# - When to use StringBuilder
Posted on 2009-12-23
I'm a VB guy transitioning to C#. In VB, I had no qualms liberally using "&" to concatenate strings. I understand that there may be some performance disadvantages, but my applications aren't demanding or high performance apps.
But C# developers tend to use more "proper" technique, so I recognize that building a string using "+" may be frowned upon, and that StringBuilder may be the preferred approach.
However, is there some threshold where + is acceptable? i.e. what if I'm only concatenating two short strings? What if 3 or 5 short strings? Is there some point at which StringBuilder offers a benefit? And is performance the only benefit of StringBuilder? Or does it have other benefits, like buffer overflow / exploit protection?
I don't need hard performance numbers--anecdotes are fine.
Some typical examples of things I need to do:
errorMsg = "An error occurred while trying to query " + objectName + " records."
sqlFilter = "CUSTNMBR LIKE '%" + filter + "%' AND DATE BETWEEN '" + date1 + "' AND '" + date2 + "'"
Is StringBuilder really necessary / recommended for these types of simple concatenations?