开发者

iPhone, Convenience Method or Alloc / Release?

开发者 https://www.devze.com 2022-12-26 01:55 出处:网络
Whilst developing for the iPhone I had a stubborn memory leak that I eventually tracked down to NSXMLParser. However whilst look开发者_StackOverflow社区ing for that it got me thinking about maybe chan

Whilst developing for the iPhone I had a stubborn memory leak that I eventually tracked down to NSXMLParser. However whilst look开发者_StackOverflow社区ing 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.


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.


[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?

0

精彩评论

暂无评论...
验证码 换一张
取 消