views:

58

answers:

6

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

+4  A: 

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.

davek
A: 

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

hova
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.
SteveO
+1  A: 

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).

Justin Niessner
A: 

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.

Dan
+1  A: 

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.

Kragen
A: 

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)

Nicolas Dorier