从循环内的大量数据中检查 属性 的有效方法

Efficient way of checking property from a large set of data inside a loop

请考虑这段通用代码:

for j = 0 to (Array.length myArray) - 1 do
    if property.(id) then
        (* do a bunch of stuff*)
done

这里,property是一个非常大的布尔数组。 在这个实验中,我们有 2 个案例:

我们希望第二种情况获胜,因为它跳过了代码执行。 但这不会因为分支条件而发生。 我们也尝试过分区 property 而不是 if 语句,但第一种情况仍然获胜。 (这些都是 OCaml 社区成员的建议)。

我们的问题定义是:我们可以检测到允许我们跳过部分代码的属性。但是使用一个大的布尔数组来保存哪个元素有这个 属性 使得对 属性 本身的检查比保存的代码执行速度慢。

因此,现在的问题更笼统:实现这个问题的更好方法是什么?

我们非常感谢社区的任何建议。

在我看来,您的问题有两种可能的解决方案:

  • 如果你还想使用for循环,那我建议使用异常退出for循环

    exception YourExn of something
    
    try
      for j = 0 to (Array.length property) - 1 do
        if property.(id) then
          (* do a bunch of stuff*)
        else raise (YourExn result)
      done
    with YourExn res -> (* do something *)
    

    YourExn 异常

  • 另一个解决方案是只写一个递归函数而不是使用for循环。我建议使用此解决方案,因为使用递归函数是函数式编程中的一种标准。

    let rec traverse property id =
      if id > (Array.length property) then
        (* exit *)
      else if property.(id) then
        (* do a bunch of stuff*)
        traverse property (id + 1)
      else
        (* exit *) in
    
    traverse property 0
    

在此处 Why is it faster to process a sorted array than an unsorted array? 阅读了类似的问题后,我的代码的最佳解决方案是编写一个无分支条件,如 节中所建议的,那么可以做什么?那个答案。