简体   繁体   中英

Java: Is there any real performance 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 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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM