繁体   English   中英

将递归 function 的结果连接到 Javascript 中的数组中的最快方法是什么?

[英]What is the fastest way to concatenate results of a recursive function into an array in Javascript?

正如标题所说,我正在寻找从递归 function 创建平面数组 output 的最有效方法。

下面的示例产生了正确的结果,但它有点慢,因为它必须为每个递归级别创建一个临时连接的点数组。

class QuadTree {

  // ...
  // some other methods
  // ...

  get points() {
    if (this.divided) {
      // concatenate and return points of all subtrees
      return this.subtrees[0].points.concat(
        this.subtrees[1].points,
        this.subtrees[2].points,
        this.subtrees[3].points
      );
    }
    // return _points array of this quadtree
    return this._points;
  }
}

有没有办法加快这个速度?

我认为这种问题在使用嵌套/树状数据结构时很常见,但我还没有找到令人满意的解决方案。

我能想到的唯一一件事就是用 function 替换您的访问器属性(或者可能在其旁边添加 function)并传递目标数组以便可以直接填充它。 就像是:

class QuadTree {

  // ...
  // some other methods
  // ...

  getDividedPoints(target = []) {
    this.subtrees[0].getDividedPoints(target);
    this.subtrees[1].getDivdedPoints(target);
    this.subtrees[2].getDivdedPoints(target);
    this.subtrees[3].getDivdedPoints(target);
    return target;
  }

  get points() {
    if (this.divided) {
      return this.getDividedPoints([]);
    }
    // return _points array of this quadtree
    return this._points;
  }
}

或者如果subtrees是一个普通数组, getDividedPoints可以是:

getDividedPoints(target = []) {
  this.subtrees.forEach(subtree => subtree.getDividedPoints(target));
  return target;
}

否则,由于我假设您要复制this.subtrees[0].points (而不是插入其中),因此concat会非常好。

如果子树可能会或可能不会被划分,您将需要 function 中的if 而我才刚刚注意到 class 的名称。 :-) 所以我可能只打四个电话:

getPoints(target) {
  if (this.divided) {
    target = target || [];
    this.subtrees[0].getPoints(target);
    this.subtrees[1].getPoints(target);
    this.subtrees[2].getPoints(target);
    this.subtrees[3].getPoints(target);
    return target;
  }
  if (target) {
    target.push.apply(target, this._points);
    return target;
  }
  return this._points; // <== If you're really okay with giving this
                       // to the caller (you were in your original code)
}

get points() {
  return this.getDividedPoints([]);
}

...或任何其他关于该基本想法的旋转。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM