1

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.

2
  • second is better, doesn't iterate twice Commented Nov 23, 2020 at 12:18
  • True, if it passes the if on approach 1. But what if it only passes the if seldomly? Commented Nov 23, 2020 at 12:19

3 Answers 3

3

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);
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

-1

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

2 Comments

I honestly have never thought about this, very good point!
this has a bad performance. it runs the .filter() method after ever iteration

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.