【问题标题】:In VBA why is comparing two doubles quicker than comparing two long在 VBA 中,为什么比较两个双精度比比较两个长
【发布时间】:2019-10-31 02:56:30
【问题描述】:

我正在尝试优化我的代码的速度。我的原始代码是比较两个价格,所以我使用的是双倍价格。但后来我想也许把它们改成 long 可能会加快这个过程。但是比较两个 double 的时间似乎几乎是比较两个 long 的一半。这是为什么呢?

将变量 m,n,p 运行为 long 或 double

Sub FastTest()
Dim x, y, z As Integer
Dim m, n, p As Double
'Dim m, n, p As Long
Dim StartTime As Double

StartTime = Timer()

'm = CLng(115658573)
'n = CLng(45357896)

m = 115658573
n = 45357896

For x = 1 To 1000
    For y = 1 To 1000
        For z = 1 To 100
            If m > n Then
                p = m + n
            End If
        Next
    Next
Next

MsgBox Timer - StartTime
End Sub

【问题讨论】:

    标签: vba compare double long-integer


    【解决方案1】:

    每个 VBA 程序员都会陷入这个陷阱。在此声明中

    Dim x, y, z As Integer
    Dim m, n, p As Double
    

    x、y、m、n 被声明为Variant,然后VBA 将在运行时决定类型。以这种方式声明变量

    Dim x As Long, y As Long, z As Long
    Dim m As Double, n As Double, p As Double
    

    然后再次运行测试并告诉我结果:)

    +1:将整数声明为Long。您可能认为只使用 2 个字节作为整数可以节省内存,但这是一种兼容性功能,VBA 无论如何都会在运行时将它们转换为 long。

    【讨论】:

    • +1 Integer 轶事。请记住,一些旧的 API 调用需要 16 位整数输入,这是必须在 VBA 中将变量声明为 Integer 的地方。
    【解决方案2】:

    首先做清楚正确的测试。

    Dim m, n, p As Double
    Debug.Print "m:=" & VarType(m) & " n:=" & VarType(n) & " p:=" & VarType(p)
    

    返回:m:=0 n:=0 p:=5

    Dim m, n, p As Double
    m = 115658573
    n = 45357896
    p = m + n
    Debug.Print "m:=" & VarType(m) & " n:=" & VarType(n) & " p:=" & VarType(p)
    

    返回:m:=3 n:=3 p:=5

    Dim m As Double
    Dim n As Double
    Dim p As Double
    Debug.Print "m:=" & VarType(m) & " n:=" & VarType(n) & " p:=" & VarType(p)
    

    返回:m:=5 n:=5 p:=5

    查看VarType function 了解有关返回值的更多信息。

    【讨论】:

    • 你总是检查mVarType,这就是为什么你的返回值是相同的,而实际上它们应该只在最后一次测试中如此。
    • @Nacorid 如我所见,初始化变量后得到“正确”类型。这就是我展示 3 个示例的原因。
    • 但是你在每个例子中检查 mVarType 3 次,当你应该检查每个例子的每个变量时
    • 哦!对不起,复制/粘贴)))
    猜你喜欢
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-22
    • 1970-01-01
    • 2020-09-14
    • 1970-01-01
    相关资源
    最近更新 更多