Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing reference on every method call or once on instance creation

Tags:

java

I'm making a simple game, and it has a single instance of a class named Game that deals with all the logic of the game.

Many of the classes in the project have a method called tick() which is called from within the Game instance 60 times per second and deals with updating information. Such instances are stored in list(s) in the Game class.

This method requires access to the Game class and currently looks like this:

MyClass {
    public void tick(Game game) {
        ...
    }
}

My question is - would it be better to do as I am doing now and pass a reference hundreds and thousands of times per second to all the instances that require it or simply pass a single reference to these instances on creation and have the classes look like so:

MyClass {
    private Game game;
    public MyClass(Game game) { this.game = game }
    public void tick() { ... }
}

Basically, how taxing it is to pass this reference so many times every second?

Thanks in advance.

Edit: Perhaps another option is to mark all the required members of the Game class as static and calling them as such without a reference at all?..

like image 388
Acidic Avatar asked Aug 07 '26 13:08

Acidic


2 Answers

It's not that taxing. You should make the decision based on design, not speed.

Does the Game passed in ever change? If not, it's probably best to pass it in during the constructor, and make the field final for clarity.

But, are there many many Games? If so, it probably makes sense to pass it in the method so you don't have to construct tons and tons of MyClass - you can make due (perhaps) with only one.

like image 199
user949300 Avatar answered Aug 11 '26 11:08

user949300


You'd probably have to profile this to get a definitive answer. You're balancing the cost of pushing an argument onto the stack and accessing the argument inside the function versus accessing an instance field from within the function. My guess is that this will be close to a wash.

If game changes identity during execution, then there's a big win for passing it as an argument every time. It doesn't sound like that applies in your case, however.

like image 20
Ted Hopp Avatar answered Aug 11 '26 11:08

Ted Hopp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!