Today's advanced e-business solutions are built around dynamic, data-driven Web applications. In many of these applications, the HTML and XML text streams sent from the Web server to the client are constructed on demand by concatenating a large number of smaller strings drawn from diverse sources such as scripts, business-tier applications, databases, and directory services.
To provide high performance and scalability in these applications, developers need efficient string-concatenation methods. This article presents such a method and compares its performance with the standard Visual Basic (VB) string-concatenation technique.
Standard VB String Concatenation
Visual Basic 6.0 provides a flexible variable-length string data type and a robust built-in string-concatenation operator (&), both of which are appropriate for many tasks. However, for concatenating many smaller strings into a large stringthe primary task required for the dynamic generation of HTML and XMLthe built-in functionality does not offer the best performance.
This is because VB variable-length strings are initially allotted a relatively small amount of memory for storage. If a program attempts to store more data in the string variable than memory has been allotted for, the variable automatically is reallocated just enough memory for its new size. As convenient as this is for the developer, memory reallocation is computationally expensive because the program must move all the data in the string to new memory locations. To make matters worse, as the string gets larger, the time required for reallocation grows longer.
Finally, because only enough memory is allocated to hold the variable at its new size, the program must reallocate memory for the string every time it performs an additional concatenation operation. So, this process becomes particularly expensive when concatenating many small strings into a large text stream, as is commonly done when dynamically generating HTML or XML.