Home > Mobile >  Should I use a for loop to iterate over my object's array?
Should I use a for loop to iterate over my object's array?

Time:09-28

I have created a DomObject class that can display boxes that move around.

jFiddle

Naturally, if I increase the number of boxes in the DomObject, the movement function takes longer to run since it is a for loop.

 beginMovement = () => {
    if (!this.timer) {
      // console.log("Begin Movement");
      this.timer = setInterval(this.movement, this.time);
    }
  };
 movement = () => {
    // here we know that its running
    let i = 0;
    while (i < this.boxes.length) {
      this.boxes[i].move();
      i  ;
    }
  }

In the case that I increase the length of this.boxes, I notice that there are performance issues.

So my main question is, should I be using a for loop in this instance? Or should I avoid using basic html for moving items all together and move onto using canvas

CodePudding user response:

Depends what your goal is. You seem to be trying to do some sort of an animation in which case using canvas/WebGL is a better option if you are going for raw speed.

Now your objects are living on the DOM, which wasn't originally designed to display fancy graphics and animations. Every design consideration for canvas was made explicitly for animation and complex bitmap operations like colorization and blurring. You never have to "find" a canvas element. You can access them far more quickly than even a cached DOM element. Even updating text elements in canvas is faster then doing so on the DOM.

Here is a related SO discussion on canvas vs DOM.

  • Related