Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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.

share|improve this question
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 Jan 5 '12 at 16:42
No, he doesn't. He needs to read on Premature Optimization. –  Boris Yankov Jan 5 '12 at 17:02

1 Answer 1

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.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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