Question

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

Was it helpful?

Solution

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 TIPS

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.

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

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

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.

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)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top