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?..
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
gamechanges 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.