Fast VBScript string class

by Jan Verhoeven, 10 November 2001

String building in VBScript is very slow. The VBScript class presented below is easy to use and much faster.

<%
  'fast string class
  class strCat
    dim index, ub, ar()

    Private Sub Class_Initialize()
      'statements
      redim ar(50)
      index=0
      ub=10
    End Sub

    Private Sub Class_Terminate()
      'statements
      erase ar
    End Sub

    public default Sub Add(value)
      ar(index)=value
      index=index+1
      if index>ub then
        ub=ub+50
        redim preserve ar(ub)
      end if
    end sub

    public Function dump
      redim preserve ar(index-1)
      dump=join(ar,"")
    end function
  end class

  'first traditional method
  t1=time
  os=""
  for i=1 to 5000
    os=os & "This is the slow method of building strings"
  next
  t2=time

  t3=time
  set cat= new strCat
  for i=1 to 5000
    cat("This is the slow method of building strings")
  next
  s= cat.dump
  set cat = nothing
  t4=time

  response.Write("Using the & operator:" & cstr(t1) & " - " & cstr(t2) &  "<br>Using the fast string class: " & cstr(t3) &  " -  cstr(t4) &  "<br>")
%>

Using strCat

First create a new instance of the class with:

  set cat= new strCat

Next you add add substrings:

  cat("add some substring to the fast string class")
  cat("add another substring to the fast string class")

When you are done dump the result string and release the object:

  s=cat.dump
  set cat=nothing