Re: ARC dealloc best pratice
Re: ARC dealloc best pratice
- Subject: Re: ARC dealloc best pratice
- From: Greg Parker <email@hidden>
- Date: Fri, 06 Feb 2015 16:18:54 -0800
> On Feb 6, 2015, at 3:27 PM, Jens Alfke <email@hidden> wrote:
>
>> On Feb 6, 2015, at 2:00 PM, Greg Parker <email@hidden <mailto:email@hidden>> wrote:
>>
>> Swift adds "unowned" references. These references are non-retaining. They differ from weak references and unsafe unretained references: unowned references fail with a runtime error if you try to access the pointed-to object after it has been deallocated.
> …
>> They are cheaper than weak references and safer than unsafe-unretained.
>
> What makes them cheaper than weak references? It sounds like they both have to do the same bookkeeping to track whether the pointed-to object is alive; the only difference is the behavior when accessing the reference after the pointed-to object is dealloced (i.e. treating the pointer as nil vs. failing with an error.) Both of those seem equivalent in complexity.
The weak reference system needs to keep track of every variable pointing to a particular object, and erase those variables when the object is deallocated. That is expensive.
The unowned reference system does not keep track of every unowned variable. Instead it keeps a count of unowned pointers to a particular object (basically a second reference count of unowned references). If an object's strong reference count reaches zero and its unowned reference count is not zero then the object's destructors are called but the storage itself is not freed. A zombie object is put in its place. If the unowned reference count later decreases to zero then the zombie is freed and everybody is happy. If an unowned reference is used and there is a zombie present, the runtime complains.
Unowned references are inefficient if a large object dies but an unowned reference to it lives on, because the object's memory won't be reclaimed until later. They are efficient when the pointed-to object lives as long or longer than the unowned reference variable.
--
Greg Parker email@hidden <mailto:email@hidden> Runtime Wrangler
_______________________________________________
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