从字符串数组创建字符串。最快的方法?

时间:2015-09-04 14:40:13

标签: vba

我有一个字符串数组(A到E),我想加入一个字符串(“A B C D E”)。我应该遍历数组还是使用Join函数?

Dim MyArray(5) as String
Dim MyString as String

MyArray(1) = "A"
MyArray(2) = "B" 
MyArray(3) = "C" 
MyArray(4) = "D" 
MyArray(5) = "E" 

哪个更快,更明智?

此?

MyString = MyArray(1)
For i = 2 To 5
    MyString = MyString & " " & MyArray(i)
Next

还是这个?

MyString = Join(MyArray, " ")

2 个答案:

答案 0 :(得分:2)

对于100k阵列

Sub test()

    Dim aArr(1 To 100000) As String
    Dim i As Long
    Dim sString As String
    Dim snTimer As Single

    FillArray aArr

    snTimer = Timer

    For i = 1 To 100000
        sString = sString & Space(1) & aArr(i)
    Next i

    Debug.Print Timer - snTimer
    snTimer = Timer

    sString = Join(aArr, Space(1))

    Debug.Print Timer - snTimer

End Sub

加入是明显的赢家

 2.050781 
 0 

原因是每次与&内存连接时都必须重新分配以容纳新数组(无论如何都是字符串)。使用Join,您只需将一个数组(源数组)复制到另一个数组(字符串),VBA已经知道它的大小。

答案 1 :(得分:2)

如果要有效地组合多个字符串,可以定义stringbuilder类。

运行下面的代码来构建一个数字字符串,最多可达一百万,只需几分之一秒(0.3秒)。构建一个数组并使用Join在同一时间(0.25秒)不远处,对Join函数的调用仅占该时间的大约10%。

如果字符串已经在数组中,则使用Join是有意义的,但是使用少量字符串时,差异不太可能明显。

Sub JoinStringTest()

Dim i As Long, t As Double
Dim sb As New StringBuilder
Dim sbRet As String
Dim joinRet As String

t = Timer
For i = 1 To 1000000
  sb.Append CStr(i)
Next
sbRet = sb.Text
Debug.Print "SB", Timer - t

t = Timer
Dim a(1000000) As String
For i = 1 To 1000000
  a(i) = CStr(i)
Next i
joinRet = Join(a, "")
Debug.Print "Join", Timer - t

Debug.Print sbRet = joinRet

End Sub