adOpenStatic Logo
Navigation
Home
FAQ
Ken's Blog
Resources
Contact Ken
Copyright 2000 -



The challenge:
Recently on the Wrox Pro-ASP list there was some discussion on which was faster: multiple string concatenations followed by a single Response.Write() call, multiple concatenations within a Response.Write() call, or multiple calls of Response.Write().

Some evidence was presented to suggest that the first option was the fastest. This contradicts everything that I know of string concatenation within VBScript, and every test result that I have seen on this. I rigged my own test to see for myself what results I would get.

TestBed
The tests were run on a Dual Pentium II 400 MHz with 128 MB 100 MHz ECC SDRAM. The server is running NT Server v4 (with SP6a) and IIS v4 with MDAC 2.5 and the v5.1 VBScript Engine.

The Results
Since this is what most people are looking for it's up the top :-) The results are in milliseconds. Divide by 1000 to get the number of seconds.

Run Number

Using concatenation

Using Multiple Response Calls in a Loop

1

6,187

47

2

6,453

47

3

6,265

31

4

6,297

47

5

6,297

46

6

6,343

47

The Code
The timer script used was the speedtimer available here from LearnASP.com.

The substantive code for the first test was:

<%
For i = 1 to 10000
   strVar = strVar & "More Blah "
Next

Response.Write(strVar)
%>

The substantive code for the 2nd test was:

<%
For i = 1 to 10000
   Response.Write("More Blah")
Next
%>

The code in its entirety can be downloaded here.

Why does VBScript concatenation take so long?
Because VBScript uses arrays to handle string concatenation, and redimensioning arrays in VBScript is extremely inefficient. The following describes this in more detail and is extracted from Microsoft's KB article Q170964.

When performing repeated concatenations of the type:

For I = 1 To N
   Dest = Dest & Source
Next

the length of time increases proportionally to N-squared. Thus, 1000 iterations will take about 100 times longer than 100 iterations. This is because Visual Basic does not just add the Source characters to the end of the Dest string; it also performs the following operations:

  • Allocates temporary memory large enough to hold the result.
  • Copies Dest to the start of the temporary area.
  • Copies Source to the end of the temporary area.
  • De-allocates the old copy of Dest.
  • Allocates memory for Dest large enough to hold the result.
  • Copies the temporary data to Dest.

Steps 2 and 6 are very expensive and basically result in the entire concatenated result being copied twice with additional overhead to allocate and de-allocate memory.

Any comments on the above are more than welcome!

Back to the experiments listing.