【问题标题】:Check if before running for loop - javascript在运行 for 循环之前检查是否 - javascript
【发布时间】:2020-11-23 12:14:58
【问题描述】:

在 Typescript (ES6) 中,我有一个以 1 ms 的间隔运行的队列,我想知道哪种方法更适合提高性能。

1.

setInterval(() => {
  //if (this._queue.filter(a => !a.running && a.cbs.length) { // incorrect
  if (this._queue.filter(a => !a.running && a.cbs.length).length) { //edit
    for (let i = 0; i < this._queue.filter(a => !a.running && a.cbs.length).length; i++) {
      ...
    }
  }
}, 1);
setInterval(() => {
  for (let i = 0; i < this._queue.filter(a => !a.running && a.cbs.length).length; i++) {
    ...
  }
}, 1);

在方法 #1 中,它显然有一行额外的代码,但我很确定 if 在每次间隔迭代时会占用更少的 CPU 计算。这是正确的吗?

在方法 #2 中,它必须定义 i,然后运行过滤器,然后尝试迭代。

这可能在性能上的差异如此之小,这可能无关紧要,但我仍然感兴趣。

【问题讨论】:

  • 第二个更好,不重复两次
  • 是的,如果它通过方法 1 的 if。但是如果它很少通过 if 怎么办?

标签: javascript typescript for-loop if-statement


【解决方案1】:

你的 if 语句不正确

if (this._queue.filter(a => !a.running && a.cbs.length) {
// this always resolves as true
// should be
if (this._queue.filter(a => !a.running && a.cbs.length).length) {

只需重复使用迭代

setInterval(() => {
  const arr = this._queue.filter(a => !a.running && a.cbs.length)
  if (arr.length) {
    for (let i = 0; i < arr.length; i++) {
      ...
    }
  }
}, 1);

【讨论】:

    【解决方案2】:

    在这两种情况下,您都会在每次迭代时评估过滤器表达式。您可以做的最好的事情是只评估一次过滤器:

    setInterval(() => {
      const queueLength = this._queue.filter(a => !a.running && a.cbs.length).length;
      for (let i = 0; i < queueLength;  i++) {
        ...
      }
    }, 1);
    

    【讨论】:

      【解决方案3】:

      注意确保在 for 之外评估过滤器的值: 否则,您将在每次迭代时评估过滤器的值,即使不依赖于迭代 i:

      您可以通过在过滤器iteretee 中添加console log 来验证这一点。

      setInterval(() => {
       for (let i = 0; i < this._queue.filter(a => {console.log(a); reurn !a.running && 
       a.cbs.length} ).length; i++) 
       {
       ...
       }
       }, 1);
      

      所以最好在循环外定义一个值为this._queue.filter(a =&gt; !a.running &amp;&amp; a.cbs.length) 的常量

      【讨论】:

      • 老实说我从来没有想过这个问题,非常好!
      • 这性能很差。它在每次迭代后运行.filter() 方法
      猜你喜欢
      • 2021-02-25
      • 2019-06-24
      • 1970-01-01
      • 2021-09-21
      • 2020-08-09
      • 2018-07-22
      • 2012-03-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多