VB Quicktakes - Faster String Manipulation
This example demonstrates a method for speeding up string concatenation. When adding characters to a string (ex. string1 = string1 & string2) VB is relatively inefficient especially when concatenating a string numerous times such as in a loop. The main reason for this is that VB must allocate memory each time the size of a string variable is increased. The example below demonstrates a more efficient method of concatenation. By allocating spaces to a string and than replacing those spaces with whatever strings are necessary can greatly improve perfomance. Using this method code will run @ 100 times faster when creating a 1 mb text file. The performance boosts grows exponentially with the size of the string being created.
Private Sub cmdTest_Click() Const ALLOCATED_SPACE = 10000000 Dim fnum As Long, currPos Dim strTest As String currPos = 1 'sets string length strTest = Space(ALLOCATED_SPACE) 'creates a string listing numbers 1 to 40000 For i = 0 To 40000 Mid(strTest, currPos, Len(CStr(i) & " ")) = CStr(i) & " " currPos = currPos + Len(CStr(i) & " ") Next 'get rid of any extra spaces strTest = Trim(strTest) fnum = FreeFile() Open App.Path & "\Test.txt" For Output As #fnum Print #fnum, strTest Close #fnum End Sub