Java: Is there any real performance cost for passing object references between looped methods

891 views Asked by At

Scenario 1:

public class Game {
    public void doSomething(Hero hero, Enemy enemy){
        if (hero.IsAlive()){
            hero.checkCollisionWith(enemy);
        }
    }
}

Scenario 2

public class Game {
    Hero hero;
    Enemy enemy;

    public Game(Hero hero, Enemy enemy) {
        this.hero = hero;
        this.enemy = enemy;        
    }

    public void doSomething() {
        if (hero.IsAlive()){
            hero.checkCollisionWith(enemy);
        }
    }
}

Now, under normal circumstances, I guess either would be acceptable, however, in a game-loop that is going to be called 60 times per second, is the first option generally to be avoided? How much of a performance hit is there for passing references through methods that are being called in a loop?

Bear in mind also that this is just an example, in the real project, there would be a lot more of these methods being called and a lot more objects involved.

Would it be wiser to give the game class the references it needs upfront (at construction) rather than constantly passing them about?

1

There are 1 answers

0
Elemental On BEST ANSWER

Parameter passing in this way is extremely efficient - the difference between calling a function without parameters and one with parameters is negligible.

Especially in the context of a game where the rendering/collisions/AI code is certainly going to be very processor intensive a small difference like this won't matter.

However from a simplicity and elegance of code point of view I think your second solution is more contained, more traditional OOP and readable.