Search code examples
javascriptphaser-frameworkstatementsmultiple-conditionsifs

Multiple conditions vs. multiple statements


Is there a difference in terms of performance between these code examples?

if (this.game.physics.arcade.overlap(this.player, this.barels) && (this.game.time.now - this.srdicka.timecheck > this.srdicka.frequency) || (this.player.position.y > this.game.height + 100)) {
  this.damage(1);
}

or

if (this.game.physics.arcade.overlap(this.player, this.barels) && (this.game.time.now - this.srdicka.timecheck > this.srdicka.frequency)) {
  this.damage(1);
}

if (this.player.position.y > this.game.height + 100) {
  this.damage(1);
}

I know that both work just fine but I'm not sure which of them is better.


Solution

  • Yes. In the first version, this...

    (this.player.position.y > this.game.height + 100)
    

    ...will only be evaluated if this...

    this.game.physics.arcade.overlap(this.player, this.barels) &&
    (this.game.time.now - this.srdicka.timecheck > this.srdicka.frequency)
    

    ...evaluates to false. In the second version it'll be evaluated no matter what. So if the expression that's in the second if in the second example is going to be expensive it could make a significant difference. As noted in the comments, the difference between your two examples also changes the logic. In this case making the second statement an else if would preserve the original logic.

    Here's an example that illustrates the difference in performance and logic with direct effects and side effects. Run it and look at the console.