asp tutorials, asp.net tutorials, sample code, and Microsoft news from 15Seconds
Data Access  |   Troubleshooting  |   Security  |   Performance  |   ADSI  |   Upload  |   Email  |   Control Building  |   Component Building  |   Forms  |   XML  |   Web Services  |   ASP.NET  |   .NET Features  |   .NET 2.0  |   App Development  |   App Architecture  |   IIS  |   Wireless
 
Pioneering Active Server
 Power Search










Active News
15 Seconds Weekly Newsletter
• Complete Coverage
• Site Updates
• Upcoming Features

More Free Newsletters
Reference
News
Articles
Code Samples
Components
Tools
New
Free
Downloads
Vendors
FAQ
Feedback
Books
Links
DL Archives
Community
Messageboard
List Servers
Mailing List
WebHosts
Consultants
Tech Jobs
15 Seconds
Home
Site Map
Press
Legal
Privacy Policy
internet.commerce














internet.com
IT
Developer
Internet News
Small Business
Personal Technology
International

Search internet.com
Advertise
Corporate Info
Newsletters
Tech Jobs
E-mail Offers

HardwareCentral
Compare products, prices, and stores at Hardware Central!

Super Fast String Concatenation

The StringBuilder class is a class to speed string concatenation in VBScript. The typical way of doing string concatenation is like so:


strVariable = strVariable & "your new string"

When performing multiple string concatenations, VBScript duplicates the original string and appends the new string at the end of it. Then it replaces the original string with the new one. This can be an incredibly costly maneuver if you are building a very large string. The StringBuilder class is there to make this much more efficient. Here is an example of how to use it.

Dim objBuilder, i
Set objBuilder = new StringBuilder

For i = 0 To 500
	objBuilder.Append("my string " & i)
Next

Response.Write objBuilder.ToString()

The concept is the same as string concatenation. You simply create your StringBuilder object, append new strings to the end, and when you're finished you simply get the string back out by calling the ToString function.

I wrote this class based on techniques I've seen other developers use, and borrowed the name from the .NET StringBuilder class, which functions exactly the same way as this VBScript class.


' Use this class to concatenate strings in a much more
' efficient manner than simply concatenating a string
' (strVariable = strVariable & "your new string")
Class StringBuilder
	Dim arr 	'the array of strings to concatenate
	Dim growthRate  'the rate at which the array grows
	Dim itemCount   'the number of items in the array

	Private Sub Class_Initialize()
		growthRate = 50
		itemCount = 0
		ReDim arr(growthRate)
	End Sub

	'Append a new string to the end of the array. If the
	'number of items in the array is larger than the
	'actual capacity of the array, then "grow" the array
	'by ReDimming it.
	Public Sub Append(ByVal strValue)
		If itemCount > UBound(arr) Then
			ReDim Preserve arr(UBound(arr) + growthRate)
		End If

		arr(itemCount) = strValue
		itemCount = itemCount + 1
	End Sub

	'Concatenate the strings by simply joining your array
	'of strings and adding no separator between elements.
	Public Function ToString() 
		ToString = Join(arr, "")
	End Function
End Class

StringBuilder.cls

For those of you who would rather perform string concatenation with VB6, just copy the following code into VB and put it in a class.


Option Explicit

Private marrStrings() As String    ' the internal array

Private mlCount As Long            ' the number of objects in the array
Private mlCapacity As Long         ' the current max number of objects that can be stored in the array
Private mlGrowthRate As Long       ' the rate of growth for the array
Private mlInitialCapacity As Long  ' the initial capacity for the array
Private mblArrayInit As Boolean    ' if the array has been initialized for the first time or not


'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

Private Sub Class_Initialize()
    ' Set default values
    mlCount = 0
    mlCapacity = 0
    mlGrowthRate = 50
    mlInitialCapacity = 50
End Sub

'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' the current number of objects in the array
Public Property Get lCount() As Long
    lCount = mlCount
End Property


' the current maximum number of objects that can be stored in the array
Public Property Get lCapacity() As Long
    lCapacity = mlCapacity
End Property


' the rate at which the array grows when the capacity is reached
Public Property Get lGrowthRate() As Long
    lGrowthRate = mlGrowthRate
End Property

Public Property Let lGrowthRate(lNewRate As Long)
    If lNewRate > 0 Then
        mlGrowthRate = lNewRate
    Else
        ' Raise an error
        Call Err.Raise(vbObjectError + 1000, "GLStringList->Let_lGrowthRate", _
                       "The Growth Rate must be greater than zero")
    End If
End Property

'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

' Adds a String to the end of the array
Public Sub Add(ByVal szString As String)
    If mblArrayInit = False Then
        ' The array has not been created
        Call InitArray
    End If
    
    ' Increase the object count
    If mlCount + 1 > mlCapacity Then
        ' Resize the array
        Call ResizeArray
    End If
    
    ' Add the object to the array
    marrStrings(mlCount) = szString
    
    mlCount = mlCount + 1
End Sub

' Gets the objects at the specified index
Public Function Item(ByVal lIndex As Long) As String
    If lIndex >= 0 And lIndex <= lCount Then
        Item = marrStrings(lIndex)
    Else
        Call Err.Raise(vbObjectError + 1002, "GLStringList->Item", "Index out of bounds")
    End If
End Function

' Sets the InitialCapacity of the ArrayList
' Has no effect once you add the first object to the array
Public Sub SetInitialCapacity(lCapacity As Long)
    If mblArrayInit = False Then
        If lCapacity > 0 Then
            mlInitialCapacity = lCapacity
        Else
            Call Err.Raise(vbObjectError + 1003, "GLArrayList->SetInitialCapacity", _
                           "The Initial Capacity must greater than zero.")
        End If
    End If
End Sub

' Retrieve the whole array, joined
Public Function GetContent() As String
    Debug.Print "Getting Content: " & Now()
    GetContent = Join(marrStrings, "")
    Debug.Print "Done Getting Content: " & Now() & vbCrLf & "---------------------------"
End Function


'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

Private Sub InitArray()
    ReDim marrStrings(mlInitialCapacity - 1) As String
    mlCapacity = mlInitialCapacity
    mblArrayInit = True
End Sub

Private Sub ResizeArray()
    ReDim Preserve marrStrings(mlCapacity + mlGrowthRate - 1) As String
    
    mlCapacity = mlCapacity + mlGrowthRate
End Sub

Submitted by Adam Sills. Orginally posted to the ASP e-mail discussion list.





email this code sample to a colleague


Support the Active Server Industry



JupiterOnlineMedia

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info


Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers