dcsimg
Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


Tip of the Day
Language: VB4,VB5,VB6
Expertise: Intermediate
Jun 10, 2000

WEBINAR:

On-Demand

Building the Right Environment to Support AI, Machine Learning and Deep Learning


Faster string appending with Mid$ command

As you probably know, the "&" operator is rather slow, especially with long strings. When you have to repeatedly append chucks of characters to the same variable, you can speed up your code using a simple trick based on the Mid$ command. The idea is that you pre-allocate a buffer long enough to accomodate for the result of your operation. Here's an example of this technique.

Suppose you want to create a string given by appending the first 10000 integers, e.g. "1 2 3 4 5 6 7 ... 9999 10000". This is the easiest way to do so:


res = ""
For i = 1 to 10000: res = res & Str(i): Next
The problem with the standard approach is that the res variable is reallocated 10000 times. This is a better way to reach the same result:

Dim res As String
Dim i As Long
Dim index As Long

' prepare a buffer long enough
res = Space(90000)
' this points to where we want to insert the string
index = 1

' here we go
For i = 1 to 10000
    substr = Str(i)
    length = Len(substr)
    ' stuff the string inside the result variable
    Mid$(res, index, length) = substr
    ' advance index
    index = index + length
Next
' drop extra chars
res = Left$(res, index - 1)

The standard code takes 2.2 seconds on my 333 MHz system computer, while the smart way takes only 0.08 seconds, so it's 25+ times faster.
Francesco Balena
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date