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

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 of these would be acceptable, however, in a game loop that would be called 60 times per second, the first option should generally be avoided? How much of the performance goes into passing references through methods called in the loop?

Keep in mind also that this is just an example, a real project would have many more methods that are called and many more objects.

Wouldn't it be wiser to give the game class the links it needs beforehand (when building) rather than passing them around all the time?

+3


source to share


1 answer


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

Especially in the context of a game in which the rendering / collision / AI code will certainly be very CPU intensive, a slight difference like this doesn't matter.



However, from the simplicity and elegance of the code point of view, I believe your second solution is more meaningful, more traditional OOP, and readable.

+2


source







All Articles