Option Explicit ' 默认的缓冲区初始大小和增长系数 Private Const DEF_INITIALSIZE As Long = 1000 Private Const DEF_GROWTH As Long = 1000 ' 缓冲区大小和增长 Private m_nInitialSize As Long Private m_nGrowth As Long ' 缓冲区和缓冲区计数器 Private m_sText As String Private m_nSize As Long Private m_nPos As Long Private Sub Class_Initialize() ' 设置大小和增长的默认值 m_nInitialSize = DEF_INITIALSIZE m_nGrowth = DEF_GROWTH ' 初始化缓冲区 InitBuffer End Sub ' 设置初始大小和增长数量 Public Sub Init(ByVal InitialSize As Long, ByVal Growth As Long) If InitialSize > 0 Then m_nInitialSize = InitialSize If Growth > 0 Then m_nGrowth = Growth End Sub ' 初始化缓冲区 Private Sub InitBuffer() m_nSize = -1 m_nPos = 1 End Sub ' 增大缓冲区 Private Sub Grow(Optional MinimimGrowth As Long) ' 初始化缓冲区(如有必要) If m_nSize = -1 Then m_nSize = m_nInitialSize m_sText = Space$(m_nInitialSize) Else ' 只是增长 Dim nGrowth As Long nGrowth = IIf(m_nGrowth > MinimimGrowth, m_nGrowth, MinimimGrowth) m_nSize = m_nSize + nGrowth m_sText = m_sText & Space$(nGrowth) End If End Sub ' 将缓冲区大小调整到当前使用的大小 Private Sub Shrink() If m_nSize > m_nPos Then m_nSize = m_nPos - 1 m_sText = RTrim$(m_sText) End If End Sub ' 添加单个文本字符串 Private Sub AppendInternal(ByVal Text As String) If (m_nPos + Len(Text)) > m_nSize Then Grow Len(Text) Mid$(m_sText, m_nPos, Len(Text)) = Text m_nPos = m_nPos + Len(Text) End Sub ' 添加一些文本字符串 Public Sub Append(ParamArray Text()) Dim nArg As Long For nArg = 0 To UBound(Text) AppendInternal CStr(Text(nArg)) Next nArg End Sub ' 返回当前字符串数据并调整缓冲区大小 Public Function ToString() As String If m_nPos > 0 Then Shrink ToString = m_sText Else ToString = "" End If End Function ' 清除缓冲区并重新初始化 Public Sub Clear() InitBuffer End Sub
此类中使用的基本原则是,在类级别将变量 (m_sText
) 用作字符串缓冲区,并使用 Space$ 函数以空格字符填充此缓冲区以将其设置为特定的大小。如果要将更多文本与现有文本连接在一起,则在检查缓冲区的大小足以存放新文本后,使用 Mid$ 函数在正确位置插入文本。ToString 函数将返回当前存储在缓冲区中的文本,并将缓冲区的大小调整为能够容纳此文本的正确长度。使用 StringBuilder 的 ASP 代码如下所示:
Function WriteHTML( Data ) Dim oSB Dim nRep Set oSB = Server.CreateObject( "StringBuilderVB.StringBuilder" ) ' 用大小和增长系数初始化缓冲区 oSB.Init 15000, 7500 For nRep = 0 to 99 oSB.Append "<TR><TD>", (nRep + 1), "</TD><TD>", _ Data( 0, nRep ), "</TD><TD>", _ Data( 1, nRep ), "</TD><TD>", _ Data( 2, nRep ), "</TD><TD>", _ Data( 3, nRep ), "</TD><TD>", _ Data( 4, nRep ), "</TD><TD>", _ Data( 5, nRep ), "</TD></TR>" Next WriteHTML = oSB.ToString() Set oSB = Nothing End Function