I’m getting out of memory exceptions from the following function when RowCollection is 50000+ and thus i need to make it more memory efficient. The function is simply needs to construct a comma separated string of the row indexes stored in RowCollection. Can anyone spot any obvious memory hungry operations in the following?
N.B RowCollection just contains a list of row indexes stored as integers.
Private Function GetCommaSeparatedString(ByRef RowIndexes As ArrayList) As String
Dim RowString As String = String.Empty
'Build a string of the row indexes
'Add one onto each index value so our indexes begin at 1
For Each Row In RowIndexes
RowString += CInt(Row.ToString) + 1 & ","
Next
'Remove the last comma
If RowString.Length > 0 Then
RowString = RowString.Substring(0, RowString.Length - 1)
End If
Return RowString
End Function
Thanks in advance.
I’m not sure why you’re getting out of memory errors, unless the string representation of your rows is extremely large, because you never have more than one or two non-garbage-collectible strings.
However, your method is horribly inefficient because it spends so much time copying the contents of half-built strings. A StringBuilder is more appropriate when building large strings, because it can be modified without re-creating the contents each time.
HOWEVER, in this case even a StringBuilder is a bad idea, because you are joining strings and there is already a method to do that: String.Join. Just use a LINQ query to do the add-one-to-index-stuff and you get a one-liner:
I would also recommend not passing by reference unless you actually need it. You aren’t modifying RowIndexes, so pass it by value. I’m also not sure why you are ToString()-ing the index then immediately parsing it. Aren’t they already integers? Just use CInt.