【问题标题】:Is there a difference between nested "if"'s and using "if x and y and z and .." regarding speed? [duplicate]关于速度,嵌套的“if”和使用“if x and y and z and ..”之间有区别吗? [复制]
【发布时间】:2015-02-05 23:16:37
【问题描述】:

我有一个简短的问题。 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 的数量会扼杀这种速度优势?

【问题讨论】:

    标签: vba ms-access if-statement flow-control


    【解决方案1】:

    单班机正在检查所有条件,无论是否有任何条件已经失败。

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

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

    这是short-circuiting in programming 的一种形式。

    【讨论】:

      【解决方案2】:

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

      所以嵌套如果结束如果我在任何一天使用多个条件!

      【讨论】:

        猜你喜欢
        • 2012-10-07
        • 1970-01-01
        • 1970-01-01
        • 2018-10-26
        • 1970-01-01
        • 2017-08-20
        • 2015-01-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多