Feb
27
2003

String Class

Fast String concatenation with the String Class

Every time you concatenate a String in Visual Basic, the String is redimensioned to the length of the new String. If you are doing multiple concatenations in a loop then this becomes very inefficient.

The String Class dimensions a buffer and only redimensions the buffer when it becomes full. So if you choose the buffer length wisely (the best size would be the final length of the string) then you can gain enormous efficiency from using the String Class.

You may notice that the CopyMemory API is used to insert the string to be appended into the buffer and that the Prepend method calls CopyMemory twice. This means that the Prepend method is approximately half as fast as the Append method (still a lot quicker than using Strings though).

Usage

Add StringClass.cls to your project

   'In this example the buffer will be redimensioned 10 times.
   'If the same loop was done with a String then it would require
   '1000 redimensions (which is 50 times slower on my computer).

   Dim s As StringClass
   Dim MyString As String
   Dim l As Long

   MyString = space(1000)

   Set s = New StringClass
   s.BufferSize = 100000
   For l = 1 To 1000
      s.Append MyString
   Next
   Set s = Nothing

Downloads

StringClass.zip - contains: StringClass.cls (1 kb)

More...