tags:

views:

62

answers:

3

If I alloc and init an object in a method that is called quite frequently, and if I don't release it immediately, does the object become a memory nightmare? Or will the alloc and init be ignored if the object is already in memory?

This is somewhat difficult for me to explain, sorry!

Thanks.

+1  A: 

Without garbage collection, if the object in question is never autoreleased, it vanishes the instance you release it. Even if the object is autoreleased, you can make your own autorelease pool and wrap your loop with it.

In garbage collection, then it's a little bit harder to predict, but the garbage collector should do a decent job of handling objects that are all allocated near to each other.

John Calsbeek
A: 

Without knowing what you're doing exactly, it's hard to say, but it sounds like you're doing:

for (...)
   [[Foo alloc] init];

In which case you'll leak, just as if you did

for (...)
    malloc(...)

or

for (...)
    new ...;

If you're in a GC environment this isn't a problem (in Obj-C 2, with GC enabled retain/release don't have any effect at all). If you're not using GC then you're leaking every object that you alloc.

Alternatively, if you're doing something like

for (...)
    [[[Foo alloc] init] autorelease]

You won't leak indefinitely, but none of your instantiated objects will be collected until you return to the top of the event loop (ie. your event handler finishes). In this case you can end up using lots of memory at once, without actually leaking it in the long term.

olliej
I'm calling this method every time a timer fires, which is a few times per second. I'm not in a GC environment. Thanks.
but what is you code doing?`[[Foo alloc] init]` or `[[[Foo alloc] init] autorelease]`?
olliej
A: 

Have you profiled your code? If so, you know if this is a hot spot. If not, your working in the dark.

You mentioned in a comment "I'm calling this method every time a timer fires, which is a few times per second", in which case its completely irrelevent, the cost of allocating memory for an object a few times a second will be completely negligible.

Peter N Lewis