user1779362
user1779362

Reputation: 1010

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.

Upvotes: 1

Views: 126

Answers (3)

habib chabbi
habib chabbi

Reputation: 98

pay attention to make sure that you evaluate the value of the filter outside the for : Otherwise you will be evaluating the value of the filter with each iteration and even if does not depend on the iteration i:

you can verify this by adding a console log inside the filter iteretee.

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

Sou it would be better to define a constant having the value this._queue.filter(a => !a.running && a.cbs.length) outside the loop

Upvotes: -1

Guerric P
Guerric P

Reputation: 31815

In both cases you are evaluating the filter expression on each iteration. The best thing you could do is evaluate the filter just once:

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

Upvotes: 3

Medet Tleukabiluly
Medet Tleukabiluly

Reputation: 11930

Your if statement is incorrect

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

Just reuse the iteration

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

Upvotes: 3

Related Questions