Article ID: 170964
Article Last Modified on 10/11/2006
For I = 1 To N
Dest = Dest & Source
Next N
the length of time increases proportionally to N-squared. Therefore,
1000 iterations will take about 100 times longer than 100 iterations. This is
because Visual Basic does not just add the Source characters to the end of the
Dest string; it also performs the following operations:
Option Explicit
' For 16-bit products, uncomment the next three lines by removing the
' single quotes and add a single quote to comment out the following
' three lines.
' Const ConcatStr = "ABC"
' Const ccIncrement = 15000
' Declare Function GetTickCount Lib "USER" () As Long
Const ConcatStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
Const ccIncrement = 50000
Private Declare Function GetTickCount Lib "KERNEL32" () As Long
Dim ccOffset As Long
Sub StdConcat(ByVal LoopCount As Long)
Dim BigStr As String, I As Long, StartTick As Long
StartTick = GetTickCount()
For I = 1 To LoopCount
BigStr = BigStr & ConcatStr
Next I
Debug.Print LoopCount; "concatenations took";
Debug.Print GetTickCount() - StartTick; "ticks"
End Sub
Sub Test_Concat()
Debug.Print "Using standard concatenation"
StdConcat 1000
StdConcat 2000
StdConcat 3000
StdConcat 4000
StdConcat 5000
Debug.Print
Debug.Print "Using pre-allocated storage and pseudo-concatenation"
MidConcat 1000
MidConcat 2000
MidConcat 3000
MidConcat 4000
MidConcat 5000
End Sub
Sub Concat(Dest As String, Source As String)
Dim L As Long
L = Len(Source)
If (ccOffset + L) >= Len(Dest) Then
If L > ccIncrement Then
Dest = Dest & Space$(L)
Else
Dest = Dest & Space$(ccIncrement)
End If
End If
Mid$(Dest, ccOffset + 1, L) = Source
ccOffset = ccOffset + L
End Sub
Sub MidConcat(ByVal LoopCount As Long)
Dim BigStr As String, I As Long, StartTick As Long
StartTick = GetTickCount()
ccOffset = 0
For I = 1 To LoopCount
Concat BigStr, ConcatStr
Next I
BigStr = Left$(BigStr, ccOffset)
Debug.Print LoopCount; "pseudo-concatenations took";
Debug.Print GetTickCount() - StartTick; "ticks"
End Sub
Using standard concatenation
1000 concatenations took 2348 ticks
2000 concatenations took 8954 ticks
3000 concatenations took 20271 ticks
4000 concatenations took 35103 ticks
5000 concatenations took 54453 ticks
Using pre-allocated storage and pseudo-concatenation
1000 pseudo-concatenations took 82 ticks
2000 pseudo-concatenations took 124 ticks
3000 pseudo-concatenations took 165 ticks
4000 pseudo-concatenations took 247 ticks
5000 pseudo-concatenations took 289 ticks306821 How To Improve String Concatenation Performance in Visual Basic .NET
Keywords: kbhowto kbprogramming KB170964