String / StringBuilder what volume do you use one over the other

Tag: stringbuilder Author: ljgis Date: 2009-10-14

It's Friday refactor time!!!

I have an object that I use to generate SQL statements.

oDb.From is set once. Then meta data may add join(s) over time till we combine it all and pass it back.

So the Q is, What # of times do I keep syntax oDb.From += before I replace it with sbFrom.Append()

Is that # 3, 4, or 15 times?

Or is it really a length of content issue, and if so what is the magical #?

TIA

Best Answer

Read http://www.codinghorror.com/blog/archives/001218.html

The StringBuilder class is designed for scenarios where you are constructing mammoth strings, and using normal string concatenation really would be too slow.

The chances are that for the sort of string lengths that you are dealing with it really wont make any difference at all - just use whatever you are most comfortable with.

Other Answer1

Totally unscientific rule of thumb: I'd do it for anything over three elements - not because of performance increase, but rather out of (hopefully) good habit.

Other Answer2

If I have to append more than two elements to a String, I almost always use StringBuilder (I find that if I append more than two, there will inevitably be more as people start adding to my code...so StringBuilder is already there for them).

Other Answer3

I'd say anything you expect to go over 1-5MB in length or anything that allocations lots of strings in little chunks.

comments:

I was considering similar types of arguments. Volume it's Size Matters kind of world ;-> I see having 3 to 4 table joins in my from clause and most are compound columns so code like : m_oConfig.DatabasePrefix + ".[" + oDb[i].TableName + "]." +oDb[i].ColumnName + ..... will be common in a foreach loop. In the end the length of the SQL segment should be under 2000 chr() outside of the where clause which can get thick. Each segment, FieldList, From, Where, Having, Gropby, Orderby is generated as part of the oDB object.

Other Answer4

It's not a total unscientific - I read an article once upon a time where in .NET string builder actually becomes more efficient after 5 concatenations. This is when I typically use a String Builder.

Also - I think readability really comes into play regarding this and I also prefer string format in some cases over both.

Other Answer5

I use StringBuilder when the number of concatenation in an algorithm grow over O(n). If the number of concatenation is O(1), most of the time readability suffer for nothing(Except if the string is very large, which is not very often).

Or when I know that there is a string that will become large enough. (More than 100k char)