Get the App
SLTechnology News&Howtos  ›  Development  › 

How to solve the performance problem of string concatenation in VBS

Shulou Source: shulou.com Published: 2022-06-03 06:46:58 11月15日 Update

This article will explain in detail how to solve the performance problem of string connection in VBS. Xiaobian thinks it is quite practical, so share it with you as a reference. I hope you can gain something after reading this article.

Of course, efficiency doesn't really matter much to the program for a small number of string concatenations, so let's consider an extreme problem: concatenating all numbers between 1 and 100000 into a string.

The simplest solution is to use & Connect directly:

The copy code is 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 takes 60.648 seconds to run on my computer, which is too inefficient. In other words, use the array to solve:

The copy code is 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, which is about 60 times faster. In this case, the size of the array can be determined in advance, and dynamic arrays must be used if the size of the array cannot be predicted. I am relatively low level, will not use dynamic array, there is no simpler way? The answer is yes, and that is the dictionary:

The copy code is 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 runtime is 1.593, twice as long as arrays, but still much faster than & and easier to use than arrays.

About "how to solve the string connection performance problem in VBS" this article is shared here, I hope the above content can be of some help to everyone, so that you can learn more knowledge, if you think the article is good, please share it for more people to see.

Tags: Code array character string question article performance dynamic size efficiency scheme more program run good practical between content dictionary that is Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MariaDB Xiaomi Linux Apple Shulou Tech Info