|
Fast string concatenation
|
Each time that you use the ampersand ("&") operator, Visual Basic allocates memory for the new string and copy the old string into the new string.
If you concatenate a lots of small strings into one big string, the operation is quite ineffective because Visual Basic allocates memory, copy, and deallocates memory a lots of times !
You can solve this problem by explicitly allocating big chunks of strings when it needed.
The following class lets you easily and efficiently concatenate strings. It automatically allocates more space when it needed, in chunks of 1000 characters.
You can download the sample project below, and see that string concatenation with this class might be much faster than doing it with ampersand operator.
Private strText As String
Public lngAllocated As Long
Public lngUsed As Long
Public lngAllocSize As Long
Private Sub Class_Initialize()
lngAllocSize = 1000
End Sub
Public Sub Add(strAddString As String)
Dim lngLen As Long
Dim lngToAllocate As Long
lngLen = Len(strAddString)
If lngLen > 0 Then
If lngUsed + lngLen > lngAllocated Then
lngToAllocate = lngAllocSize * (1 + (lngUsed + lngLen - lngAllocated) \ lngAllocSize)
strText = strText & String$(lngToAllocate, " ")
lngAllocated = lngAllocated + lngToAllocate
End If
Mid$(strText, lngUsed + 1, lngLen) = strAddString
lngUsed = lngUsed + lngLen
End If
End Sub
Public Function GetStr() As String
GetStr = Mid$(strText, 1, lngUsed)
End Function
|
|
|