StringBuilder Size Algorithm

When I posted about this before, someone noted that cycling through all the items would be a performance hit. Well, as you can see, I'm really only cycling thru the tables in the DataSet, and in the case of the DataReader, I'm only accessing a property that already exists.

For DataSets:

Dim FieldCount As Int32 = 0

'Algorithm for setting the minimum StringBuilder size initially, so that we do not have to continually re-allocate memory
'This should increase performance
For Each dt In dataset.Tables
     FieldCount += dt.Columns.Count * dt.Rows.Count
Next
sb.EnsureCapacity(FieldCount * 25)

For DataReaders:

Dim FieldCount As Int32 = 0

'Algorithm for setting the minimum StringBuilder size initially, so that we do not have to continually re-allocate memory
'This should increase performance
sb.EnsureCapacity(dr.FieldCount * 25)

This should be fairly adequate in most situations. You want to undershoot by less than half, because if you can do that, then it will only resize once, having reached it's maximum capacity a little more than halfway through. When the StringBuilder resizes, it doubles it size, so this logic only makes sense. You don't ever want it to resize more than once tho, otherwise you'll have way too much wasted memory.

No Comments