哪种数组写方法更好(CPU成本)?

时间:2018-09-24 14:06:22

标签: arrays excel vba performance

我有一个很大的复杂VBA脚本是我为工作而编写的。我正在清理它的过程中,发现我可以用比我以前更动态的方式定义接缝。

最初我是这样定义我的数组为String的:

Dim header_arr(6) As String
Dim header_arr_2(4) As String

header_arr(0) = "esn"
header_arr(1) = "vin"
header_arr(2) = "last gps update time"
header_arr(3) = "status"
header_arr(4) = "account name"
header_arr(5) = "vehicle #"

header_arr_2(0) = "esn"
header_arr_2(1) = "vin"
header_arr_2(2) = "last gps update time"
header_arr_2(3) = "status"
header_arr_2(4) = "vehicle #"

然后我在研究如何分配数组,并设法将其简化为:

Dim header_arr

header_arr = Array("esn", "vin", "last gps update time", "status", "account name", "vehicle #")
' Function call with this first Array

header_arr = Array("esn", "vin", "last gps update time", "status", "vehicle #")
' Function call with this second Array

我的问题是这个

我知道对于脚本的这一简单部分来说,CPU开销不是多余的,但是对于更大的Array,如果有任何区别,那么编写数组的最低CPU开销的方法是什么?

我无法在定义数组的不同方法之间找到很多性能差异。

1 个答案:

答案 0 :(得分:1)

好的,所以我用变量数组和字符串数组进行了测试。让两者都运行几次,似乎带有未类型化数组的版本甚至更快。

但更重要的一课:字符串处理本身(这是一个相当简单的过程,包含一个字符串和数字)消耗了75%的运行时-因此数组本身的数据类型并不重要。 / p>

一个额外的说明:通过引用将数组传递给子例程1000次是如此之快,以至于我无法测量它。 val传递它杀死了我的擅长领域。但是,按值传递数组几乎可以确保您绝对不希望这样做。

我使用了以下代码:

Option Explicit

Private mlngStart As Long
Private Declare Function GetTickCount Lib "kernel32" () As Long

Const size = 3000000

Dim startTime As Long
Public Sub StartTimer()
    startTime = GetTickCount
End Sub

Public Function EndTimer() As Long
    EndTimer = (GetTickCount - startTime)
End Function


Sub b1()

    StartTimer
    Dim i As Long
    Dim s(size)
    For i = 1 To size
        s(i) = "ABC"
    Next i
    Debug.Print "untyped, size = " & size, EndTimer
End Sub

Sub b2()
    StartTimer
    Dim i As Long
    Dim s(size) As String
    For i = 1 To size
        s(i) = "ABC"
    Next i
    Debug.Print "as string, size = " & size, EndTimer
End Sub

结果为

untyped, size = 3000000      312 
untyped, size = 3000000      313 
untyped, size = 3000000      313 
untyped, size = 3000000      297 
untyped, size = 3000000      313 
as string, size = 3000000    328 
as string, size = 3000000    313 
as string, size = 3000000    328 
as string, size = 3000000    344 
as string, size = 3000000    313 

我将分配更改为s(i) = "ABC" & i,并得到以下结果:

untyped, size = 3000000      922 
untyped, size = 3000000      953 
untyped, size = 3000000      938 
untyped, size = 3000000      1015 
untyped, size = 3000000      953 
as string, size = 3000000    1140 
as string, size = 3000000    1156 
as string, size = 3000000    1157 
as string, size = 3000000    1125 
as string, size = 3000000    1125