3

I know this is hard to answer without examples, so I'm looking for general principles or guidelines here. I'm thinking within the realm of small- to medium-sized mobile games and apps.

I've read a few times the object reuse is a touchstone of creating efficient programs. So, I generally strive to reuse everything possible. But, then I came to realize that every object I'm keeping around has to exist somewhere in memory, so it's begun to seem inefficient. I've thought it would be fine, as long as I'm not trying to render the objects' visual or auditory aspects. And I've feared that construction and re-construction of these objects would be too expensive to perform every time I just want to toggle their presence.

Let's say, for instance, I've got a GUI comprised of 30 different objects that each represent a screen state-- buttons, panes, text, a background, maybe some animated UI components. Does it seem more sensible to initialize and de-initialize these objects, keeping them around in memory, but disabling their rendering, animations, etc? Or should I just be destroying these things and re-creating them?

Other examples of things I keep around might be game objects like non-playable characters, weapons, items, etc.

2
  • Sounds like you want to read up on Singleton Pattern and Disposable (C# uses IDisposable) and when to use each, and when to use neither.
    – StuperUser
    Commented Jan 5, 2012 at 16:42
  • 9
    No, he doesn't. He needs to read on Premature Optimization. Commented Jan 5, 2012 at 17:02

1 Answer 1

9

Premature Optimization - Just Say No!

Having multiple objects is an important abstraction over the raw memory access you would be left with if not for Object Oriented Programming.

Creating an object, is reasonably inexpensive operation on even the most modest hardware available. You should not avoid it by default.

The special case, where a new object creation is expensive justifies the use of Object Pool Pattern.

Sharing memory between similar objects, frequently found in games, can be helped with the Flyweight Pattern.

As a simple example, using a compiled language (C#, Java, C++) on a modern PC, you can create millions of simple objects in a single second.

Remember: Any optimization should be done only after you have determined that your code is slow, and only to the parts that are slow.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.