Jump to content

Best way to apply a method to all elements in a group?


fariazz
 Share

Recommended Posts

So far I've encountered different options and was wondering if there is any of them that should be preferred or is better practice (I'm feeling inclined for 3, but I might be missing something). All three work (tested):

// option 1

  Phaser.Actions.Call(this.enemies.getChildren(), function(enemy) {
    enemy.speed = Math.random() * 2 + 1;
  }, this);

// option 2
  this.enemies.children.each(function(enemy) {
    enemy.speed = Math.random() * 2 + 1;
  }, this);

// option 3, native js
this.enemies.getChildren().forEach(function(enemy) {
    enemy.speed = Math.random() * 2 + 1;
  }, this);

 

Edited by fariazz
added option 3
Link to comment
Share on other sites

I'd think they're all much of a muchness perf-wise and ergonomically, although I did have to read option 1 twice to work out `.Call` was an iterator, seeing a `forEach` or `each` is a dead give away that you're iterating over a list.

I think its still true that forEach is way way slower in most browsers than a for loop, if this is part of a critical path then maybe want to switch out and use a for loop and just deal with it that its slightly more awkward for you as a developer (should probably check that Phaser doesn't do this for you under the hood in option 2, sounds to me like exactly the sort of place it would help you squeeze extra perf out of your code).

Link to comment
Share on other sites

12 hours ago, mattstyles said:

I think its still true that forEach is way way slower in most browsers than a for loop, if this is part of a critical path then maybe want to switch out and use a for loop and just deal with it that its slightly more awkward for you as a developer (should probably check that Phaser doesn't do this for you under the hood in option 2, sounds to me like exactly the sort of place it would help you squeeze extra perf out of your code).

Good point!

Option 2 also uses a for loop ( Phaser.Structs.Set#each )

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...