Arc and autorelease

  • Without Arc, this:

    NSString *s = [ [ NSString alloc ] initWithFormat: ...];
    [ someCollection addObject: s ];
    [ s release ];

    is clearly more efficient (because not using autoreleasepools) than:

    NSString *s = [ NSString stringWithFormat: ...];
    [ someCollection addObject: s ];

    But what about Arc?
    Is the compiler clever enough to make both versions equally efficient?
    Or should one still avoid using the convenience method stringWithFormat: ?

    Kind regards,

    Gerriet.
  • On May 24, 2012, at 3:14 AM, Gerriet M. Denkmann wrote:

    > Without Arc, this:
    >
    > NSString *s = [ [ NSString alloc ] initWithFormat: ...];
    > [ someCollection addObject: s ];
    > [ s release ];
    >
    > is clearly more efficient (because not using autoreleasepools) than:
    >
    > NSString *s = [ NSString stringWithFormat: ...];
    > [ someCollection addObject: s ];
    >
    > But what about Arc?
    > Is the compiler clever enough to make both versions equally efficient?

    Maybe.  You can't know if the NSString implementation was itself compiled with ARC.  If it was, then there is a *possible* optimization that can avoid the autorelease+retain.  However, you can't rely on this.

    > Or should one still avoid using the convenience method stringWithFormat: ?

    Are you programming for iOS?  The recommendation for that is still to avoid autoreleased objects so as to keep the high-water mark of memory usage down.  For Mac OS X it's never been that big a concern except for code in a loop or the like.

    Regards,
    Ken
  • On May 24, 2012, at 1:14 AM, Gerriet M. Denkmann wrote:

    > Without Arc, this:
    >
    > NSString *s = [ [ NSString alloc ] initWithFormat: ...];
    > [ someCollection addObject: s ];
    > [ s release ];
    >
    > is clearly more efficient (because not using autoreleasepools) than:
    >
    > NSString *s = [ NSString stringWithFormat: ...];
    > [ someCollection addObject: s ];
    >
    > But what about Arc?
    > Is the compiler clever enough to make both versions equally efficient?
    > Or should one still avoid using the convenience method stringWithFormat: ?

    As a rule, ARC tries to keep objects out of the local autorelease pool, and can usually succeed at that even when working with code that is not itself compiled under ARC. I would use whichever method makes sense to you and only worry about high watermark issues if you discover a performance issue.
    --
    David Duncan
previous month may 2012 next month
MTWTFSS
  1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31      
Go to today