I’m using Instruments to try to determine if there are places in my application that I could be more efficient with use of memory. I’ve taken the time to get somewhat familiar with Instruments but I’m generally a newbie with hunting memory management issues having come from a Java background. I seem to be using about 1.82mb by calls to this method:
+ (NSString *)stringFromDateWithFormat:(NSDate *)date withFormat:(NSString *)format { NSDateFormatter *dateFormatter; NSString *result; if (nil == date || nil == format) return nil; result = nil; if (nil != (dateFormatter = [[NSDateFormatter allocWithZone:[self zone]] init])) { [dateFormatter setDateFormat:format]; if (nil != (result = [dateFormatter stringFromDate:date])) { [dateFormatter release]; return result; } [dateFormatter release]; } return nil; }
As I’m releasing the date formatter I’m wondering if the NSString result is my issue. It seems to me that the stringFromDate library call would return an autoreleased object so there’s nothing I can do to ‘manually’ manage it. A bit unsure of how to optimize this method.
Is this method getting called a lot of times in a loop? Autoreleased objects only get released when the NSAutoreleasePool they’re in gets released. As I understand it, the default autorelease pool is created and release every event loop. It’s possible you’re creating too many autoreleased objects in the course of a single event loop. The solution is to create your own NSAutoreleasePool in an appropriate place, and release it to clear up autoreleased objects. An extreme example that illustrates the point:
In that example, the current pool is released every 10,000 iterations and a new one is created. You can read more about memory management in the Memory Management Programming Guide section on autorelease pools.