Re: Question about garbage collection
Re: Question about garbage collection
- Subject: Re: Question about garbage collection
- From: Bill Bumgarner <email@hidden>
- Date: Sun, 03 Jan 2010 10:40:48 -0800
On Jan 3, 2010, at 9:59 AM, Michael Abendroth wrote:
> When I write something like:
>
> while (true) {
> NSString *s = [[NSString alloc] initWithString:@"applejuice"];
> }
>
> Will s be garbage collected? If not, how can I make sure it does get
> deallocated by garbage collection.
I'm not entirely sure what pattern you are asking about; repeated allocations? ...writing your own looping construct?
In any case, the rules of collection for the stack are thus:
A thread's stack is conservatively scanned. That is, every slot that *could* hold a pointer is scanned to see if it holds a pointer, regardless of type declaration. Thus, as long as there is a reference to an object on the stack, that object will remain uncollected. If the reference is overwritten (and no references exist elsewhere in the heap and the object has not been CFRetain'd), the object will be collected.
The stack has to be conservatively scanned because the C ABI makes no guarantee about stack layout and the compiler is free to put values wherever it sees fit, including overwriting values with other values as a part of optimization (which is the same reason why you sometimes can't print local variable's values when debugging optimized code).
This can cause an object to live longer than expected. In practice, this rarely happens, though, as run loops zero the stack -- only to the depth needed -- on each loop (as does Grand Central).
If you are writing your own looping construct, you can call objc_clear_stack(...) to clear the stack at appropriate times, typically when the stack is as shallow as possible. Prior to Snow Leopard, writing your own looping construct was relatively rare in Cocoa. With Snow Leopard's addition of Grand Central Dispatch, writing your own looping construct is actively discouraged (though, certainly, there are still reasons to do so).
b.bum
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden