嵌套"if"和使用"if x and y and z and .."的速度之间有区别吗?



>我有一个简短的问题。VBA 之间有什么区别吗

if x1 and x2 and x3 and ... and x10 then
    foo
end if

if x1 then
  if x2 then
    if x3 then
      ...
      foo
    end if
  end if
end if

关于速度?

更具体地说:我有 10 列包含数据,需要逐行比较数据库中的重复项数据(在这种情况下,SELECT DISTINCT 之类的东西不起作用)。

我可以想象,使用

x1 = recordset.fields("Field1").value
if x1 then
  x2 = recordset.fields("Field2").value
  if x2 then
    x3 = recordset.fields("Field3").value
    if x3 then
      ...
      foo
    end if
  end if
end if

将比

x1 = recordset.fields("Field1").value
x2 = recordset.fields("Field2").value
...
if x1 and x2 and x3 and ... and x10 then
    foo
end if

因为我不必从记录集中读取所有数据。还是 ifs 的数量会扼杀这种速度优势?

单行正在检查所有条件,如果其中任何一个已经失败,则忽略它们。

Sub Main()
    If Check And Check And Check Then
    End If
End Sub
Function Check() As Boolean
    Debug.Print "checked"
    Check = False
End Function

嵌套的 ifs 是更好的选择,因为一旦一个条件失败,代码执行将立即跳转到 else/end if 块,而不是尝试评估所有其他条件。

这是编程中的一种短路形式。

  • VBA 短路"和"替代方案

  • 当第一个参数为假时,VBA"And"运算符是否计算第二个参数?

嵌套 If 在优化方面会是一个更好的选择。如果条件失败,嵌套 If 将忽略所有其他以下内容,但是,如果使用 AND(或)OR 的一行不会优化,因为在做出判决之前会执行每个条件。此外,代码的可读性和可维护性在嵌套 If 中要好得多(前提是它们正确缩进)。

所以嵌套如果结束 如果每天为我使用多个条件!

最新更新