Performance issues with string concatenation in VBS _VBS

Source: Internet
Author: User
Of course, for a small number of string connections, efficiency doesn't have much impact on the program, so let's consider an extreme problem: connecting all numbers from 1 to 100000 to a string.

The simplest solution is to use the & connection directly:
Copy Code code as follows:

Begin = Timer
For i = 1 to 100000
str = str & CSTR (i)
Next
WScript.Echo Str
finish = Timer
WScript.Echo Finish-begin

But this program on my computer needs to run for 60.648 seconds, inefficient. To change a scheme, use an array to resolve:
Copy Code code as follows:

Begin = Timer
Dim arr (100000)
For i = 1 to 100000
Arr (i) = i
Next
str = Join (arr, "")
WScript.Echo Str
finish = Timer
WScript.Echo Finish-begin

This time it took only 0.742 seconds, about 60 times times faster. In this problem the size of the array can be determined beforehand, and a dynamic array must be used if the size of the array cannot be predicted. I'm low level, not using a dynamic array, is there a simpler way? The answer is yes, that's the dictionary:
Copy Code code as follows:

Begin = Timer
Set Odic = CreateObject ("Scripting.Dictionary")
For i = 1 to 100000
Odic.add I, CStr (i)
Next
str = Join (Odic.items, "")
WScript.Echo Str
finish = Timer
WScript.Echo Finish-begin

The elapsed time is 1.593, twice times that of the array, but it is much faster than & and is easier to use than arrays.

Summarizing the:& join symbol is relatively inefficient and can be used when connecting to a small number of strings, but you should use the Join function + array when connecting a large number of strings.
Original: http://demon.tw/programming/vbs-string-concatenation.html

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.