I have a GameEngine class which is a sprite, and a GameModel which is a Singleton and holds a lot of the data.
I then get the data with
GameModel.getInstance().variable;
my game engine has a lot of them in it now and i was wondering if it would be more efficient if i had a reference to the GameModel in my GameEngine instead of creating it all the time
private var _data:GameModel = GameModel.getInstance();
trace(_data.variable);
I have a pretty strong feeling it will be more efficient but if anyone could let me know for sure and let me know if you can potentially see flaws with this method that would be much appreciated, cheers, rory.
It’s definitely a good idea to store the instance in a property, since the lookup will be faster, but also because it lowers the GameEngine’s knowledge of the GameModel’s implementation details.
For example, imagine you’ve got a bunch of
GameModel.getInstance()calls inside your GameEngine class and you decide to drop the singleton behaviour. You’ll be rewriting all those calls, however if you’d cached the instance in a property you’d only need to rewrite one line.That said, forget about singletons altogether, they’re a far greater evil than premature optimization, but if you MUST use one, at least store the instance in a property in your client classes.