views:

129

answers:

2

Whilst developing for the iPhone I had a stubborn memory leak that I eventually tracked down to NSXMLParser. However whilst looking for that it got me thinking about maybe changing a lot of my convenience methods to alloc/release. Is there any good reason for doing that? In a large app I can see how releasing memory yourself quickly is a better idea, but in a small app is there any other difference between the two methods.

NSNumber *numberToAdd = [NSNumber numberWithInt:intValue];
dostuff ...

OR

NSNumber *numberToAdd = [[NSNumber alloc] initWithInt:intValue];
doStuff ...
[numberToAdd release];

cheers gary.

+4  A: 

There is no difference memory-management-wise between those two methods. In a gui app, an NSAutoreleasePool is created and destroyed on every spin of the run loop, so small objects like this will most likely be destroyed within a few microseconds. The only time I could see it mattering is if you're on a secondary thread and you're about to create a TON of autoreleased objects. However, you're always welcome to create and destroy your own autorelease pools.

Dave DeLong
Much appreciated Dave, just what I was after. I really just wanted to check I was on the right track.
fuzzygoat
@Dave: Thank you, your answer was really helpful :)
abelito
A: 

[NSNumber numberWithInt:1] === [[[NSNumber alloc] initWithInt:1] autorelease]

Even though numberWithInt: is more convenient, it is more code to execute. Internally, autorelease is sticking that object onto an ever growing array.

If you are in a loop doing lots of allocations, you might benefit from managing memory yourself. In the normal course of UI operations, the cost of autorelease is negligible.

The actual definition of lots is up to you and a profiler. At what point does the benefit of more readable code lose to the benefit of faster code?

drawnonward