fariazz

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

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

Share this post


Link to post
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).

Share this post


Link to post
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 )

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...

  • Recently Browsing   0 members

    No registered users viewing this page.