lundi 23 novembre 2020

Check if before running for loop - javascript

In Typescript (ES6), I have a queue running on an interval of 1 ms and I want to know which approach is better practice for performance.

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);
    

    In approach #1, it obviously has an extra line of code, but I am pretty sure the if would take less CPU computation on each iteration of interval. Is this correct?

    In approach #2, it has to define i and then run the filter and then attempt to iterate.

    This may be such a low difference in performance it may not matter, but I am interested nonetheless.

    Aucun commentaire:

    Enregistrer un commentaire